<!DOCTYPE html>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta name="generator" content="rustdoc">
    <title>The Rust Reference Manual(Rust参考手册)</title>

    <link rel="stylesheet" type="text/css" href="The%20Rust%20Reference%20Manual_files/rust.css">

    <link rel="shortcut icon" href="The%20Rust%20Reference%20Manual_files/favicon.ico">
<link href="The%20Rust%20Reference%20Manual_files/css.css" rel="stylesheet" type="text/css">
<style>
  /* Display the full TOC */
  nav {
    column-count: auto;
    -moz-column-count: auto;
    -webkit-column-count: auto;
  }
  nav ul ul {
    display: block;
    padding-left: 2em;
  }
  #influences blockquote p:last-child {
    color: #999;
  }
</style>


</head>
<body>
    <!--[if lte IE 8]>
    <div class="warning">
        This old browser is unsupported and will most likely display funky
        things.
    </div>
    <![endif]-->

    <div id="versioninfo">
  <img src="The%20Rust%20Reference%20Manual_files/rust-logo-32x32-blk.png" alt="" height="32" width="32"><br>
  <span class="white-sticker"><a href="http://rust-lang.org/">Rust</a> 0.11-pre-nightly</span><br>
</div>


    <h1 class="title">The Rust Reference Manual(Rust参考手册)</h1>
    <nav id="TOC"><ul>
<li><a href="#introduction">1 Introduction(介绍)</a><ul>
<li><a href="#disclaimer">1.1 Disclaimer(免责声明)</a><ul></ul></li></ul></li>
<li><a href="#notation">2 Notation(符号)</a><ul>
<li><a href="#unicode-productions">2.1 Unicode productions(Unicode 产生式)</a><ul></ul></li>
<li><a href="#string-table-productions">2.2 String table productions(字符串表产生式)</a><ul></ul></li></ul></li>
<li><h5>以下第3节属于编译原理中的词法分析部分说明</h5></li>
<li><a href="#lexical-structure">3 Lexical structure(词法结构)</a><ul>
<li><a href="#input-format">3.1 Input format(输入格式)</a><ul></ul></li>
<li><a href="#special-unicode-productions">3.2 Special Unicode Productions(特定Unicode产生式)</a><ul>
<li><a href="#identifiers">3.2.1 Identifiers(标识)</a><ul></ul></li>
<li><a href="#delimiter-restricted-productions">3.2.2 Delimiter-restricted productions(限制分隔符产生式)</a><ul></ul></li></ul></li>
<li><a href="#comments">3.3 Comments(备注)</a><ul></ul></li>
<li><a href="#whitespace">3.4 Whitespace(空白)</a><ul></ul></li>
<li><a href="#tokens">3.5 Tokens(单词)</a><ul>
<li><a href="#keywords">3.5.1 Keywords(关键词)</a><ul></ul></li>
<li><a href="#literals">3.5.2 Literals(文字)</a><ul>
<li><a href="#character-and-string-literals">3.5.2.1 Character and string literals(字符和字符串文字)</a><ul></ul></li>
<li><a href="#number-literals">3.5.2.2 Number literals(数字文字)</a><ul>
<li><a href="#integer-literals">3.5.2.2.1 Integer literals(整数文字)</a><ul></ul></li>
<li><a href="#floating-point-literals">3.5.2.2.2 Floating-point literals(浮点文字)</a><ul></ul></li>
<li><a href="#unit-and-boolean-literals">3.5.2.2.3 Unit and boolean literals(Unit和布尔文字)</a><ul></ul></li></ul></li></ul></li>
<li><a href="#symbols">3.5.3 Symbols(符号)</a><ul></ul></li></ul></li>
<li><a href="#paths">3.6 Paths(路径)</a><ul></ul></li></ul></li>
<li><a href="#syntax-extensions">4 Syntax extensions(语法扩展)</a><ul>
<li><a href="#macros">4.1 Macros(宏)</a><ul>
<li><a href="#macro-by-example">4.1.1 Macro By Example(宏例子)</a><ul></ul></li>
<li><a href="#parsing-limitations">4.1.2 Parsing limitations(解析限制)</a><ul></ul></li></ul></li>
<li><a href="#syntax-extensions-useful-for-the-macro-author">4.2 Syntax extensions useful for the macro author(宏撰写有用的扩展语法)</a><ul></ul></li></ul></li>
<li><a href="#crates-and-source-files">5 Crates and source files(箱和源代码)</a><ul></ul></li>
<li><a href="#items-and-attributes">6 Items and attributes(项目和属性)</a><ul>
<li><a href="#items">6.1 Items(项目)</a><ul>
<li><a href="#type-parameters">6.1.1 Type Parameters(类型参数)</a><ul></ul></li>
<li><a href="#modules">6.1.2 Modules(模块)</a><ul>
<li><a href="#view-items">6.1.2.1 View items(可见性项目)</a><ul>
<li><a href="#extern-crate-declarations">6.1.2.1.1 Extern crate declarations(外部箱声明)</a><ul></ul></li>
<li><a href="#use-declarations">6.1.2.1.2 Use declarations(use 声明)</a><ul></ul></li></ul></li></ul></li>
<li><a href="#functions">6.1.3 Functions(函数)</a><ul>
<li><a href="#generic-functions">6.1.3.1 Generic functions(泛性函数)</a><ul></ul></li>
<li><a href="#unsafety">6.1.3.2 Unsafety(unsafety 不安全)</a><ul>
<li><a href="#unsafe-functions">6.1.3.2.1 Unsafe functions(不安全函数)</a><ul></ul></li>
<li><a href="#unsafe-blocks">6.1.3.2.2 Unsafe blocks(不安全块)</a><ul></ul></li>
<li><a href="#behavior-considered-unsafe">6.1.3.2.3 Behavior considered unsafe(认为不安全的行为)</a><ul></ul></li>
<li><a href="#behaviour-not-considered-unsafe">6.1.3.2.4 Behaviour not considered unsafe(不认为是不安全的行为)</a><ul></ul></li></ul></li>
<li><a href="#diverging-functions">6.1.3.3 Diverging functions(发散函数)</a><ul></ul></li>
<li><a href="#extern-functions">6.1.3.4 Extern functions(外部函数)</a><ul></ul></li></ul></li>
<li><a href="#type-definitions">6.1.4 Type definitions(类型定义)</a><ul></ul></li>
<li><a href="#structures">6.1.5 Structures(结构)</a><ul></ul></li>
<li><a href="#enumerations">6.1.6 Enumerations(枚举)</a><ul></ul></li>
<li><a href="#static-items">6.1.7 Static items(静态项目)</a><ul>
<li><a href="#mutable-statics">6.1.7.1 Mutable statics(可变静态)</a><ul></ul></li></ul></li>
<li><a href="#traits">6.1.8 Traits(特性或接口)</a><ul></ul></li>
<li><a href="#implementations">6.1.9 Implementations(实现)</a><ul></ul></li>
<li><a href="#external-blocks">6.1.10 External blocks(外部块)</a><ul></ul></li></ul></li>
<li><a href="#visibility-and-privacy">6.2 Visibility and Privacy(可见性和隐私)</a><ul>
<li><a href="#re-exporting-and-visibility">6.2.1 Re-exporting and Visibility(重新输出和可见性)</a><ul></ul></li>
<li><a href="#glob-imports-and-visibility">6.2.2 Glob imports and Visibility(通配输入和可见性)</a><ul></ul></li></ul></li>
<li><a href="#attributes">6.3 Attributes(属性)</a><ul>
<li><a href="#crate-only-attributes">6.3.1 Crate-only attributes(Crate-仅有属性)</a><ul></ul></li>
<li><a href="#module-only-attributes">6.3.2 Module-only attributes(Module-仅有属性)</a><ul></ul></li>
<li><a href="#function-only-attributes">6.3.3 Function-only attributes(函数仅有属性)</a><ul></ul></li>
<li><a href="#static-only-attributes">6.3.4 Static-only attributes(静态仅有属性)</a><ul></ul></li>
<li><a href="#ffi-attributes">6.3.5 FFI attributes(FFI属性)</a><ul></ul></li>
<li><a href="#miscellaneous-attributes">6.3.6 Miscellaneous attributes(杂项属性)</a><ul></ul></li>
<li><a href="#conditional-compilation">6.3.7 Conditional compilation(条件编译)</a><ul></ul></li>
<li><a href="#lint-check-attributes">6.3.8 Lint check attributes(Lint检查属性)</a><ul></ul></li>
<li><a href="#language-items">6.3.9 Language items(语言项目)</a><ul>
<li><a href="#built-in-traits">6.3.9.1 Built-in Traits(内建特性或接口)</a><ul></ul></li>
<li><a href="#operators">6.3.9.2 Operators(运算符)</a><ul></ul></li>
<li><a href="#types">6.3.9.3 Types(类型)</a><ul></ul></li>
<li><a href="#marker-types">6.3.9.4 Marker types(标记类型)</a><ul></ul></li></ul></li>
<li><a href="#inline-attributes">6.3.10 Inline attributes(内联属性)</a><ul></ul></li>
<li><a href="#deriving">6.3.11 Deriving(发散)</a><ul></ul></li>
<li><a href="#stability">6.3.12 Stability(稳定性)</a><ul></ul></li>
<li><a href="#compiler-features">6.3.13 Compiler Features(编译器功能)</a><ul></ul></li></ul></li></ul></li>
<li><a href="#statements-and-expressions">7 Statements and expressions(语句和表达式)</a><ul>
<li><a href="#statements">7.1 Statements(语句)</a><ul>
<li><a href="#declaration-statements">7.1.1 Declaration statements(声明语句)</a><ul>
<li><a href="#item-declarations">7.1.1.1 Item declarations(项目声明)</a><ul></ul></li>
<li><a href="#slot-declarations">7.1.1.2 Slot declarations(插槽声明)</a><ul></ul></li></ul></li>
<li><a href="#expression-statements">7.1.2 Expression statements(表达式语句)</a><ul></ul></li></ul></li>
<li><a href="#expressions">7.2 Expressions(表达式)</a><ul>
<li><a href="#lvalues,-rvalues-and-temporaries">7.2.0.1 Lvalues, rvalues and temporaries(左值,右值和临时值)</a><ul></ul></li>
<li><a href="#moved-and-copied-types">7.2.0.2 Moved and copied types(移动和复制类型)</a><ul></ul></li>
<li><a href="#literal-expressions">7.2.1 Literal expressions(文字表达式)</a><ul></ul></li>
<li><a href="#path-expressions">7.2.2 Path expressions(路径表达式)</a><ul></ul></li>
<li><a href="#tuple-expressions">7.2.3 Tuple expressions(元组表达式)</a><ul></ul></li>
<li><a href="#structure-expressions">7.2.4 Structure expressions(结构表达式)</a><ul></ul></li>
<li><a href="#block-expressions">7.2.5 Block expressions(块表达式)</a><ul></ul></li>
<li><a href="#method-call-expressions">7.2.6 Method-call expressions(方法调用表达式)</a><ul></ul></li>
<li><a href="#field-expressions">7.2.7 Field expressions(字段表达式)</a><ul></ul></li>
<li><a href="#vector-expressions">7.2.8 Vector expressions(向量表达式)</a><ul></ul></li>
<li><a href="#index-expressions">7.2.9 Index expressions(索引表达式)</a><ul></ul></li>
<li><a href="#unary-operator-expressions">7.2.10 Unary operator expressions(一元运算符表达式)</a><ul></ul></li>
<li><a href="#binary-operator-expressions">7.2.11 Binary operator expressions(二元运算符表达式)</a><ul>
<li><a href="#arithmetic-operators">7.2.11.1 Arithmetic operators(算数运算符)</a><ul></ul></li>
<li><a href="#bitwise-operators">7.2.11.2 Bitwise operators(位运算符)</a><ul></ul></li>
<li><a href="#lazy-boolean-operators">7.2.11.3 Lazy boolean operators(惰性布尔运算符)</a><ul></ul></li>
<li><a href="#comparison-operators">7.2.11.4 Comparison operators(比较运算符)</a><ul></ul></li>
<li><a href="#type-cast-expressions">7.2.11.5 Type cast expressions(类型转换表达式)</a><ul></ul></li>
<li><a href="#assignment-expressions">7.2.11.6 Assignment expressions(复制表达式)</a><ul></ul></li>
<li><a href="#compound-assignment-expressions">7.2.11.7 Compound assignment expressions(复合赋值表达式)</a><ul></ul></li>
<li><a href="#operator-precedence">7.2.11.8 Operator precedence(运算符优先权)</a><ul></ul></li></ul></li>
<li><a href="#grouped-expressions">7.2.12 Grouped expressions(分组表达式)</a><ul></ul></li>
<li><a href="#call-expressions">7.2.13 Call expressions(调用表达式)</a><ul></ul></li>
<li><a href="#lambda-expressions">7.2.14 Lambda expressions(Lambda表达式)</a><ul></ul></li>
<li><a href="#while-loops">7.2.15 While loops(While Loops循环)</a><ul></ul></li>
<li><a href="#infinite-loops">7.2.16 Infinite loops(无限循环)</a><ul></ul></li>
<li><a href="#break-expressions">7.2.17 Break expressions(中断表达式)</a><ul></ul></li>
<li><a href="#continue-expressions">7.2.18 Continue expressions(连续表达式)</a><ul></ul></li>
<li><a href="#for-expressions">7.2.19 For expressions(For表达式)</a><ul></ul></li>
<li><a href="#if-expressions">7.2.20 If expressions(If表达式)</a><ul></ul></li>
<li><a href="#match-expressions">7.2.21 Match expressions(匹配表达式)</a><ul></ul></li>
<li><a href="#return-expressions">7.2.22 Return expressions(返回表达式)</a><ul></ul></li></ul></li></ul></li>
<li><a href="#type-system">8 Type system(类型系统,介绍Rust数据类型章节)</a><ul>
<li><a href="#types-1">8.1 Types(类型)</a><ul>
<li><a href="#primitive-types">8.1.1 Primitive types(基本类型)</a><ul>
<li><a href="#machine-types">8.1.1.1 Machine types(机器类型)</a><ul></ul></li>
<li><a href="#machine-dependent-integer-types">8.1.1.2 Machine-dependent integer types(机器相关整数类型)</a><ul></ul></li></ul></li>
<li><a href="#textual-types">8.1.2 Textual types(文本类型)</a><ul></ul></li>
<li><a href="#tuple-types">8.1.3 Tuple types(元组类型)</a><ul></ul></li>
<li><a href="#vector-types">8.1.4 Vector types(矢量类型)</a><ul></ul></li>
<li><a href="#structure-types">8.1.5 Structure types(结构类型)</a><ul></ul></li>
<li><a href="#enumerated-types">8.1.6 Enumerated types(枚举类型)</a><ul></ul></li>
<li><a href="#recursive-types">8.1.7 Recursive types(递归类型)</a><ul></ul></li>
<li><a href="#pointer-types">8.1.8 Pointer types(指针类型)</a><ul></ul></li>
<li><a href="#function-types">8.1.9 Function types(函数类型)</a><ul></ul></li>
<li><a href="#closure-types">8.1.10 Closure types(闭包类型)</a><ul></ul></li>
<li><a href="#object-types">8.1.11 Object types(对象类型)</a><ul></ul></li>
<li><a href="#type-parameters-1">8.1.12 Type parameters(类型参数)</a><ul></ul></li>
<li><a href="#self-types">8.1.13 Self types(self 类型)</a><ul></ul></li></ul></li>
<li><a href="#type-kinds">8.2 Type kinds(类型种类)</a><ul></ul></li></ul></li>
<li><a href="#memory-and-concurrency-models">9 Memory and concurrency models(内存和并发模型)</a><ul>
<li><a href="#memory-model">9.1 Memory model(内存模型)</a><ul>
<li><a href="#memory-allocation-and-lifetime">9.1.1 Memory allocation and lifetime(内存申请和生命周期)</a><ul></ul></li>
<li><a href="#memory-ownership">9.1.2 Memory ownership(内存所有权)</a><ul></ul></li>
<li><a href="#memory-slots">9.1.3 Memory slots(内存插槽)</a><ul></ul></li>
<li><a href="#owned-boxes">9.1.4 Owned boxes(自有的封箱)</a><ul></ul></li></ul></li>
<li><a href="#tasks">9.2 Tasks(任务)</a><ul>
<li><a href="#communication-between-tasks">9.2.1 Communication between tasks(任务间通讯)</a><ul></ul></li>
<li><a href="#task-lifecycle">9.2.2 Task lifecycle(任务生命周期)</a><ul></ul></li>
<li><a href="#task-scheduling">9.2.3 Task scheduling(任务调度)</a><ul></ul></li></ul></li></ul></li>
<li><a href="#runtime-services,-linkage-and-debugging">10 Runtime services, linkage and debugging(运行时服务,链接和调试)</a><ul>
<li><a href="#memory-allocation">10.0.1 Memory allocation(内存申请)</a><ul></ul></li>
<li><a href="#built-in-types">10.0.2 Built in types(内建类型)</a><ul></ul></li>
<li><a href="#task-scheduling-and-communication">10.0.3 Task scheduling and communication(任务调度和通讯)</a><ul></ul></li>
<li><a href="#linkage">10.0.4 Linkage(链接)</a><ul></ul></li>
<li><a href="#logging-system">10.0.5 Logging system(日志系统)</a><ul>
<li><a href="#logging-expressions">10.0.5.1 Logging Expressions(日志表达式)</a><ul></ul></li></ul></li></ul></li>
<li><a href="#appendix:-rationales-and-design-tradeoffs">11 Appendix: Rationales and design tradeoffs(基本原理和设计权衡)</a><ul></ul></li>
<li><a href="#appendix:-influences-and-further-references">12 Appendix: Influences and further references(进一步的影响和参考)</a><ul>
<li><a href="#influences">12.1 Influences(影响)</a><ul></ul></li></ul></li></ul></nav>
<h1 id="introduction" class="section-header"><a href="#introduction">1 Introduction(介绍)</a></h1>
<p>This document is the reference manual for the Rust programming language. It
provides three kinds of material:</p>

<ul>
<li>Chapters that formally define the language grammar and, for each
construct, informally describe its semantics and give examples of its
use.</li>
<li>Chapters that informally describe the memory model, concurrency model,
runtime services, linkage model and debugging facilities.</li>
<li>Appendix chapters providing rationale and references to languages that
influenced the design.</li>
</ul>

<p>This document does not serve as a tutorial introduction to the
language. Background familiarity with the language is assumed. A separate
<a href="http://static.rust-lang.org/doc/master/tutorial.html">tutorial</a> document is available to help acquire such background familiarity.</p>

<p>This document also does not serve as a reference to the <a href="http://static.rust-lang.org/doc/master/std/index.html">standard</a>
library included in the language distribution. Those libraries are
documented separately by extracting documentation attributes from their
source code.</p>

<h2 id="disclaimer" class="section-header"><a href="#disclaimer">1.1 Disclaimer(免责声明)</a></h2>
<p>Rust is a work in progress. The language continues to evolve as the design
shifts and is fleshed out in working code. Certain parts work, certain parts
do not, certain parts will be removed or changed.</p>

<p>This manual is a snapshot written in the present tense. All features described
exist in working code unless otherwise noted, but some are quite primitive or
remain to be further modified by planned work. Some may be temporary. It is a
<em>draft</em>, and we ask that you not take anything you read here as final.</p>

<p>If you have suggestions to make, please try to focus them on <em>reductions</em> to
the language: possible features that can be combined or omitted. We aim to
keep the size and complexity of the language under control.</p>

<blockquote>
<p><strong>Note:</strong> The grammar for Rust given in this document is rough and
very incomplete; only a modest number of sections have accompanying grammar
rules. Formalizing the grammar accepted by the Rust parser is ongoing work,
but future versions of this document will contain a complete
grammar. Moreover, we hope that this grammar will be extracted and verified
as LL(1) by an automated grammar-analysis tool, and further tested against the
Rust sources. Preliminary versions of this automation exist, but are not yet
complete.</p>
</blockquote>

<h1 id="notation" class="section-header"><a href="#notation">2 Notation(符号)</a></h1>
<p>Rust's grammar is defined over Unicode codepoints, each conventionally
denoted <code>U+XXXX</code>, for 4 or more hexadecimal digits <code>X</code>. <em>Most</em> of Rust's
grammar is confined to the ASCII range of Unicode, and is described in this
document by a dialect of Extended Backus-Naur Form (EBNF), specifically a
dialect of EBNF supported by common automated LL(k) parsing tools such as
<code>llgen</code>, rather than the dialect given in ISO 14977. The dialect can be
defined self-referentially as follows:</p>

<pre><code class="language-{.notrust">grammar : rule + ;
rule    : nonterminal ':' productionrule ';' ;
productionrule : production [ '|' production ] * ;
production : term * ;
term : element repeats ;
element : LITERAL | IDENTIFIER | '[' productionrule ']' ;
repeats : [ '*' | '+' ] NUMBER ? | NUMBER ? | '?' ;</code></pre>

<p>Where:</p>

<ul>
<li>Whitespace in the grammar is ignored.</li>
<li>Square brackets are used to group rules.</li>
<li><code>LITERAL</code> is a single printable ASCII character, or an escaped hexadecimal
 ASCII code of the form <code>\xQQ</code>, in single quotes, denoting the corresponding
 Unicode codepoint <code>U+00QQ</code>.</li>
<li><code>IDENTIFIER</code> is a nonempty string of ASCII letters and underscores.</li>
<li>The <code>repeat</code> forms apply to the adjacent <code>element</code>, and are as follows:

<ul>
<li><code>?</code> means zero or one repetition</li>
<li><code>*</code> means zero or more repetitions</li>
<li><code>+</code> means one or more repetitions</li>
<li>NUMBER trailing a repeat symbol gives a maximum repetition count</li>
<li>NUMBER on its own gives an exact repetition count</li>
</ul></li>
</ul>

<p>This EBNF dialect should hopefully be familiar to many readers.</p>

<h2 id="unicode-productions" class="section-header"><a href="#unicode-productions">2.1 Unicode productions(Unicode 产生式)</a></h2>
<p>A few productions in Rust's grammar permit Unicode codepoints outside the ASCII range.
We define these productions in terms of character properties specified in the Unicode standard,
rather than in terms of ASCII-range codepoints.
The section <a href="#special-unicode-productions">Special Unicode Productions</a> lists these productions.</p>

<h2 id="string-table-productions" class="section-header"><a href="#string-table-productions">2.2 String table productions(字符串表产生式)</a></h2>
<p>Some rules in the grammar — notably <a href="#unary-operator-expressions">unary
operators</a>, <a href="#binary-operator-expressions">binary
operators</a>, and <a href="#keywords">keywords</a> —
are given in a simplified form: as a listing of a table of unquoted,
printable whitespace-separated strings. These cases form a subset of
the rules regarding the <a href="#tokens">token</a> rule, and are assumed to be
the result of a lexical-analysis phase feeding the parser, driven by a
DFA, operating over the disjunction of all such string table entries.</p>

<p>When such a string enclosed in double-quotes (<code>"</code>) occurs inside the
grammar, it is an implicit reference to a single member of such a string table
production. See <a href="#tokens">tokens</a> for more information.</p>

<h1 id="lexical-structure" class="section-header"><a href="#lexical-structure">3 Lexical structure</a></h1>
<h2 id="input-format" class="section-header"><a href="#input-format">3.1 Input format(输入格式)</a></h2>
<p>Rust input is interpreted as a sequence of Unicode codepoints encoded in UTF-8,
normalized to Unicode normalization form NFKC.
Most Rust grammar rules are defined in terms of printable ASCII-range codepoints,
but a small number are defined in terms of Unicode properties or explicit<p>
NFKC(Normalization Form KC K的意思compatibility避免和另外一个简称C：composition混淆  )
Rust把输入作为用UTF-8编码的Unicode序列,用NFKC规范化格式.
大多数Rust语法规则都是用可打印的ASCII范围的码位
但也有少数使用Unicode属性或明确的码位列表.
codepoint lists. <sup id="fnref1"><a href="#fn1" rel="footnote">1</a></sup></p>

<h2 id="special-unicode-productions" class="section-header"><a href="#special-unicode-productions">3.2 Special Unicode Productions(特定Unicode产生式)</a></h2>
<p>The following productions in the Rust grammar are defined in terms of Unicode properties:
	<br/>在Rust语法里下列产生式是用Unicode属性定义的:<br/>
<code>ident</code>, <code>non_null</code>, <code>non_star</code>, <code>non_eol</code>, <code>non_slash_or_star</code>, <code>non_single_quote</code> and <code>non_double_quote</code>.</p>
<h3 id="identifiers" class="section-header"><a href="#identifiers">3.2.1 Identifiers(标识)</a></h3>
<p>The <code>ident</code> production is any nonempty Unicode string of the following form:</p>
<br/>ident 产生式是用任何非空的下列形式的Unicode字符串<br/>
<ul>
<li>The first character has property <code>XID_start</code></li>
第一个字符具有属性<code>XID_start</code>
<li>The remaining characters have property <code>XID_continue</code></li>
其余的字符有属性<code>XID_continue</code>
</ul>

<p>that does <em>not</em> occur in the set of <a href="#keywords">keywords</a>.</p>

<p>Note: <code>XID_start</code> and <code>XID_continue</code> as character properties cover the
character ranges used to form the more familiar C and Java language-family
identifiers.</p>

<h3 id="delimiter-restricted-productions" class="section-header"><a href="#delimiter-restricted-productions">3.2.2 Delimiter-restricted productions(限制分隔符产生式)</a></h3>
<p>Some productions are defined by exclusion of particular Unicode characters:</p>

<ul>
<li><code>non_null</code> is any single Unicode character aside from <code>U+0000</code> (null)</li>
<li><code>non_eol</code> is <code>non_null</code> restricted to exclude <code>U+000A</code> (<code>'\n'</code>)</li>
<li><code>non_star</code> is <code>non_null</code> restricted to exclude <code>U+002A</code> (<code>*</code>)</li>
<li><code>non_slash_or_star</code> is <code>non_null</code> restricted to exclude <code>U+002F</code> (<code>/</code>) and <code>U+002A</code> (<code>*</code>)</li>
<li><code>non_single_quote</code> is <code>non_null</code> restricted to exclude <code>U+0027</code>  (<code>'</code>)</li>
<li><code>non_double_quote</code> is <code>non_null</code> restricted to exclude <code>U+0022</code> (<code>"</code>)</li>
</ul>

<h2 id="comments" class="section-header"><a href="#comments">3.3 Comments(备注)</a></h2>
<pre><code class="language-{.notrust">comment : block_comment | line_comment ;
block_comment : "/*" block_comment_body * '*' + '/' ;
block_comment_body : [block_comment | character] * ;
line_comment : "//" non_eol * ;</code></pre>
<pre>
<code class="language-{.notrust">备注 : 块备注 | 行备注 ;
块备注 : "/*" 块备注体 * '*' + '/' ;
块备注体 : [块备注内容 | 字符] * ;
行备注 : "//" non_eol * ;</code></pre>
<p>Comments in Rust code follow the general C++ style of line and block-comment forms,
with no nesting of block-comment delimiters.</p>

<p>Line comments beginning with exactly <em>three</em> slashes (<code>///</code>), and block
comments beginning with exactly one repeated asterisk in the block-open
sequence (<code>/**</code>), are interpreted as a special syntax for <code>doc</code>
<a href="#attributes">attributes</a>.  That is, they are equivalent to writing
<code>#[doc="..."]</code> around the body of the comment (this includes the comment
characters themselves, ie <code>/// Foo</code> turns into <code>#[doc="/// Foo"]</code>).</p>

<p>Non-doc comments are interpreted as a form of whitespace.</p>
非文档注解都被解释作为空白处理.
<h2 id="whitespace" class="section-header"><a href="#whitespace">3.4 Whitespace(空白)</a></h2>
<pre><code class="language-{.notrust">whitespace_char : '\x20' | '\x09' | '\x0a' | '\x0d' ;
whitespace : [ whitespace_char | comment ] + ;</code></pre>

<p>The <code>whitespace_char</code> production is any nonempty Unicode string consisting of any
of the following Unicode characters: <code>U+0020</code> (space, <code>' '</code>), <code>U+0009</code> (tab,
<code>'\t'</code>), <code>U+000A</code> (LF, <code>'\n'</code>), <code>U+000D</code> (CR, <code>'\r'</code>).</p>

<p>Rust is a "free-form" language, meaning that all forms of whitespace serve
only to separate <em>tokens</em> in the grammar, and have no semantic significance.</p>

<p>A Rust program has identical meaning if each whitespace element is replaced
with any other legal whitespace element, such as a single space character.</p>

<h2 id="tokens" class="section-header"><a href="#tokens">3.5 Tokens(单词)</a></h2>
<pre><code class="language-{.notrust">simple_token : keyword | unop | binop ;
token : simple_token | ident | literal | symbol | whitespace token ;</code></pre>

<p>Tokens are primitive productions in the grammar defined by regular
(non-recursive) languages. "Simple" tokens are given in <a href="#string-table-productions">string table
production</a> form, and occur in the rest of the
grammar as double-quoted strings. Other tokens have exact rules given.</p>

<h3 id="keywords" class="section-header"><a href="#keywords">3.5.1 Keywords(关键词)</a></h3>
<p>The keywords are the following strings:</p>

<pre><code class="language-{.notrust">as
box break
crate
else enum extern
false fn for
if impl in
let loop
match mod mut
priv proc pub
ref return
self static struct super
true trait type
unsafe use
while</code></pre>

<p>Each of these keywords has special meaning in its grammar,
and all of them are excluded from the <code>ident</code> rule.</p>

<h3 id="literals" class="section-header"><a href="#literals">3.5.2 Literals(文字)</a></h3>
<p>A literal is an expression consisting of a single token, rather than a
sequence of tokens, that immediately and directly denotes the value it
evaluates to, rather than referring to it by name or some other evaluation
rule. A literal is a form of constant expression, so is evaluated (primarily)
at compile time.</p>

<pre><code class="language-{.notrust">literal : string_lit | char_lit | num_lit ;</code></pre>

<h4 id="character-and-string-literals" class="section-header"><a href="#character-and-string-literals">3.5.2.1 Character and string literals(字符和字符串文字)</a></h4>
<pre><code class="language-{.notrust">char_lit : '\x27' char_body '\x27' ;
string_lit : '"' string_body * '"' | 'r' raw_string ;

char_body : non_single_quote
          | '\x5c' [ '\x27' | common_escape ] ;

string_body : non_double_quote
            | '\x5c' [ '\x22' | common_escape ] ;
raw_string : '"' raw_string_body '"' | '#' raw_string '#' ;

common_escape : '\x5c'
              | 'n' | 'r' | 't' | '0'
              | 'x' hex_digit 2
              | 'u' hex_digit 4
              | 'U' hex_digit 8 ;

hex_digit : 'a' | 'b' | 'c' | 'd' | 'e' | 'f'
          | 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
          | dec_digit ;
oct_digit : '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' ;
dec_digit : '0' | nonzero_dec ;
nonzero_dec: '1' | '2' | '3' | '4'
           | '5' | '6' | '7' | '8' | '9' ;</code></pre>

<p>A <em>character literal</em> is a single Unicode character enclosed within two
<code>U+0027</code> (single-quote) characters, with the exception of <code>U+0027</code> itself,
which must be <em>escaped</em> by a preceding U+005C character (<code>\</code>).</p>

<p>A <em>string literal</em> is a sequence of any Unicode characters enclosed within
two <code>U+0022</code> (double-quote) characters, with the exception of <code>U+0022</code>
itself, which must be <em>escaped</em> by a preceding <code>U+005C</code> character (<code>\</code>),
or a <em>raw string literal</em>.</p>

<p>Some additional <em>escapes</em> are available in either character or non-raw string
literals. An escape starts with a <code>U+005C</code> (<code>\</code>) and continues with one of
the following forms:</p>

<ul>
<li>An <em>8-bit codepoint escape</em> escape starts with <code>U+0078</code> (<code>x</code>) and is
followed by exactly two <em>hex digits</em>. It denotes the Unicode codepoint
equal to the provided hex value.</li>
<li>A <em>16-bit codepoint escape</em> starts with <code>U+0075</code> (<code>u</code>) and is followed
by exactly four <em>hex digits</em>. It denotes the Unicode codepoint equal to
the provided hex value.</li>
<li>A <em>32-bit codepoint escape</em> starts with <code>U+0055</code> (<code>U</code>) and is followed
by exactly eight <em>hex digits</em>. It denotes the Unicode codepoint equal to
the provided hex value.</li>
<li>A <em>whitespace escape</em> is one of the characters <code>U+006E</code> (<code>n</code>), <code>U+0072</code>
(<code>r</code>), or <code>U+0074</code> (<code>t</code>), denoting the unicode values <code>U+000A</code> (LF),
<code>U+000D</code> (CR) or <code>U+0009</code> (HT) respectively.</li>
<li>The <em>backslash escape</em> is the character <code>U+005C</code> (<code>\</code>) which must be
escaped in order to denote <em>itself</em>.</li>
</ul>

<p>Raw string literals do not process any escapes. They start with the character
<code>U+0072</code> (<code>r</code>), followed zero or more of the character <code>U+0023</code> (<code>#</code>) and a
<code>U+0022</code> (double-quote) character. The <em>raw string body</em> is not defined in the
EBNF grammar above: it can contain any sequence of Unicode characters and is
terminated only by another <code>U+0022</code> (double-quote) character, followed by the
same number of <code>U+0023</code> (<code>#</code>) characters that preceded the opening <code>U+0022</code>
(double-quote) character.</p>

<p>All Unicode characters contained in the raw string body represent themselves,
the characters <code>U+0022</code> (double-quote) (except when followed by at least as
many <code>U+0023</code> (<code>#</code>) characters as were used to start the raw string literal) or
<code>U+005C</code> (<code>\</code>) do not have any special meaning.</p>

<p>Examples for string literals:</p>
<pre class="rust "><span class="string">"foo"</span>; <span class="string">r"foo"</span>;<span class="comment">                     // foo
</span><span class="string">"\"foo\""</span>; <span class="string">r#""foo""#</span>;<span class="comment">             // "foo"

</span><span class="string">"foo #\"# bar"</span>;
<span class="string">r##"foo #"# bar"##</span>;<span class="comment">                // foo #"# bar

</span><span class="string">"\x52"</span>; <span class="string">"R"</span>; <span class="string">r"R"</span>;<span class="comment">                 // R
</span><span class="string">"\\x52"</span>; <span class="string">r"\x52"</span>;<span class="comment">                  // \x52
</span></pre>

<h4 id="number-literals" class="section-header"><a href="#number-literals">3.5.2.2 Number literals(数字文字)</a></h4>
<pre><code class="language-{.notrust">num_lit : nonzero_dec [ dec_digit | '_' ] * num_suffix ?
        | '0' [       [ dec_digit | '_' ] * num_suffix ?
              | 'b'   [ '1' | '0' | '_' ] + int_suffix ?
              | 'o'   [ oct_digit | '_' ] + int_suffix ?
              | 'x'   [ hex_digit | '_' ] + int_suffix ? ] ;

num_suffix : int_suffix | float_suffix ;

int_suffix : 'u' int_suffix_size ?
           | 'i' int_suffix_size ? ;
int_suffix_size : [ '8' | '1' '6' | '3' '2' | '6' '4' ] ;

float_suffix : [ exponent | '.' dec_lit exponent ? ] ? float_suffix_ty ? ;
float_suffix_ty : 'f' [ '3' '2' | '6' '4' ] ;
exponent : ['E' | 'e'] ['-' | '+' ] ? dec_lit ;
dec_lit : [ dec_digit | '_' ] + ;</code></pre>

<p>A <em>number literal</em> is either an <em>integer literal</em> or a <em>floating-point
literal</em>. The grammar for recognizing the two kinds of literals is mixed,
as they are differentiated by suffixes.</p>

<h5 id="integer-literals" class="section-header"><a href="#integer-literals">3.5.2.2.1 Integer literals(整数文字)</a></h5>
<p>An <em>integer literal</em> has one of four forms:</p>

<ul>
<li>A <em>decimal literal</em> starts with a <em>decimal digit</em> and continues with any
mixture of <em>decimal digits</em> and <em>underscores</em>.</li>
<li>A <em>hex literal</em> starts with the character sequence <code>U+0030</code> <code>U+0078</code>
(<code>0x</code>) and continues as any mixture hex digits and underscores.</li>
<li>An <em>octal literal</em> starts with the character sequence <code>U+0030</code> <code>U+006F</code>
(<code>0o</code>) and continues as any mixture octal digits and underscores.</li>
<li>A <em>binary literal</em> starts with the character sequence <code>U+0030</code> <code>U+0062</code>
(<code>0b</code>) and continues as any mixture binary digits and underscores.</li>
</ul>

<p>An integer literal may be followed (immediately, without any spaces) by an
<em>integer suffix</em>, which changes the type of the literal. There are two kinds
of integer literal suffix:</p>

<ul>
<li>The <code>i</code> and <code>u</code> suffixes give the literal type <code>int</code> or <code>uint</code>,
respectively.</li>
<li>Each of the signed and unsigned machine types <code>u8</code>, <code>i8</code>,
<code>u16</code>, <code>i16</code>, <code>u32</code>, <code>i32</code>, <code>u64</code> and <code>i64</code>
give the literal the corresponding machine type.</li>
</ul>

<p>The type of an <em>unsuffixed</em> integer literal is determined by type inference.
If an integer type can be <em>uniquely</em> determined from the surrounding program
context, the unsuffixed integer literal has that type.  If the program context
underconstrains the type, the unsuffixed integer literal's type is <code>int</code>; if
the program context overconstrains the type, it is considered a static type
error.</p>

<p>Examples of integer literals of various forms:</p>
<pre class="rust "><span class="number">123</span>; <span class="number">0xff00</span>;<span class="comment">                       // type determined by program context
                                   // defaults to int in absence of type
                                   // information

</span><span class="number">123u</span>;<span class="comment">                              // type uint
</span><span class="number">123_u</span>;<span class="comment">                             // type uint
</span><span class="number">0xff_u8</span>;<span class="comment">                           // type u8
</span><span class="number">0o70_i16</span>;<span class="comment">                          // type i16
</span><span class="number">0b1111_1111_1001_0000_i32</span>;<span class="comment">         // type i32
</span></pre>

<h5 id="floating-point-literals" class="section-header"><a href="#floating-point-literals">3.5.2.2.2 Floating-point literals(浮点文字)</a></h5>
<p>A <em>floating-point literal</em> has one of two forms:</p>

<ul>
<li>Two <em>decimal literals</em> separated by a period
character <code>U+002E</code> (<code>.</code>), with an optional <em>exponent</em> trailing after the
second decimal literal.</li>
<li>A single <em>decimal literal</em> followed by an <em>exponent</em>.</li>
</ul>

<p>By default, a floating-point literal has a generic type, but will fall back to
<code>f64</code>. A floating-point literal may be followed (immediately, without any
spaces) by a <em>floating-point suffix</em>, which changes the type of the literal.
There are two floating-point suffixes: <code>f32</code>, and <code>f64</code> (the 32-bit and 64-bit
floating point types).</p>

<p>Examples of floating-point literals of various forms:</p>
<pre class="rust "><span class="number">123.0</span>;<span class="comment">                             // type f64
</span><span class="number">0.1</span>;<span class="comment">                               // type f64
</span><span class="number">0.1f32</span>;<span class="comment">                            // type f32
</span><span class="number">12E+99_f64</span>;<span class="comment">                        // type f64
</span></pre>

<h5 id="unit-and-boolean-literals" class="section-header"><a href="#unit-and-boolean-literals">3.5.2.2.3 Unit and boolean literals(Unit和布尔文字)</a></h5>
<p>The <em>unit value</em>, the only value of the type that has the same name, is written as <code>()</code>.
The two values of the boolean type are written <code>true</code> and <code>false</code>.</p>

<h3 id="symbols" class="section-header"><a href="#symbols">3.5.3 Symbols(符号)</a></h3>
<pre><code class="language-{.notrust">symbol : "::" "-&gt;"
       | '#' | '[' | ']' | '(' | ')' | '{' | '}'
       | ',' | ';' ;</code></pre>

<p>Symbols are a general class of printable <a href="#tokens">token</a> that play structural
roles in a variety of grammar productions. They are catalogued here for
completeness as the set of remaining miscellaneous printable tokens that do not
otherwise appear as <a href="#unary-operator-expressions">unary operators</a>, <a href="#binary-operator-expressions">binary
operators</a>, or <a href="#keywords">keywords</a>.</p>

<h2 id="paths" class="section-header"><a href="#paths">3.6 Paths(路径)</a></h2>
<pre><code class="language-{.notrust">expr_path : [ "::" ] ident [ "::" expr_path_tail ] + ;
expr_path_tail : '&lt;' type_expr [ ',' type_expr ] + '&gt;'
               | expr_path ;

type_path : ident [ type_path_tail ] + ;
type_path_tail : '&lt;' type_expr [ ',' type_expr ] + '&gt;'
               | "::" type_path ;</code></pre>

<p>A <em>path</em> is a sequence of one or more path components <em>logically</em> separated by
a namespace qualifier (<code>::</code>). If a path consists of only one component, it may
refer to either an <a href="#items">item</a> or a <a href="#memory-slots">slot</a> in a local
control scope. If a path has multiple components, it refers to an item.</p>

<p>Every item has a <em>canonical path</em> within its crate, but the path naming an
item is only meaningful within a given crate. There is no global namespace
across crates; an item's canonical path merely identifies it within the crate.</p>

<p>Two examples of simple paths consisting of only identifier components:</p>
<pre class="rust "><span class="ident">x</span>;
<span class="ident">x</span>::<span class="ident">y</span>::<span class="ident">z</span>;
</pre>

<p>Path components are usually <a href="#identifiers">identifiers</a>, but the trailing
component of a path may be an angle-bracket-enclosed list of type
arguments. In <a href="#expressions">expression</a> context, the type argument list is
given after a final (<code>::</code>) namespace qualifier in order to disambiguate it
from a relational expression involving the less-than symbol (<code>&lt;</code>). In type
expression context, the final namespace qualifier is omitted.</p>

<p>Two examples of paths with type arguments:</p>
<pre class="rust "><span class="kw">type</span> <span class="ident">T</span> <span class="op">=</span> <span class="ident">HashMap</span><span class="op">&lt;</span><span class="ident">int</span>,<span class="kw-2">~</span><span class="ident">str</span><span class="op">&gt;</span>;<span class="comment">  // Type arguments used in a type expression
</span><span class="kw">let</span> <span class="ident">x</span> <span class="op">=</span> <span class="ident">id</span>::<span class="op">&lt;</span><span class="ident">int</span><span class="op">&gt;</span>(<span class="number">10</span>);<span class="comment">       // Type arguments used in a call expression
</span></pre>

<p>Paths can be denoted with various leading qualifiers to change the meaning of
how it is resolved:</p>

<ul>
<li><p>Paths starting with <code>::</code> are considered to be global paths where the
components of the path start being resolved from the crate root. Each
identifier in the path must resolve to an item.</p>
<pre class="rust "><span class="kw">mod</span> <span class="ident">a</span> {
  <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">foo</span>() {}
}
<span class="kw">mod</span> <span class="ident">b</span> {
  <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">foo</span>() {
      ::<span class="ident">a</span>::<span class="ident">foo</span>();<span class="comment"> // call a's foo function
  </span>}
}
</pre></li>
<li><p>Paths starting with the keyword <code>super</code> begin resolution relative to the
parent module. Each further identifier must resolve to an item</p>
<pre class="rust "><span class="kw">mod</span> <span class="ident">a</span> {
  <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">foo</span>() {}
}
<span class="kw">mod</span> <span class="ident">b</span> {
  <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">foo</span>() {
      <span class="ident">super</span>::<span class="ident">a</span>::<span class="ident">foo</span>();<span class="comment"> // call a's foo function
  </span>}
}
</pre></li>
<li><p>Paths starting with the keyword <code>self</code> begin resolution relative to the
current module. Each further identifier must resolve to an item.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">foo</span>() {}
<span class="kw">fn</span> <span class="ident">bar</span>() {
  <span class="self">self</span>::<span class="ident">foo</span>();
}
</pre></li>
</ul>

<h1 id="syntax-extensions" class="section-header"><a href="#syntax-extensions">4 Syntax extensions(语法扩展)</a></h1>
<p>A number of minor features of Rust are not central enough to have their own
syntax, and yet are not implementable as functions. Instead, they are given
names, and invoked through a consistent syntax: <code>name!(...)</code>. Examples
include:</p>

<ul>
<li><code>format!</code> : format data into a string</li>
<li><code>env!</code> : look up an environment variable's value at compile time</li>
<li><code>file!</code>: return the path to the file being compiled</li>
<li><code>stringify!</code> : pretty-print the Rust expression given as an argument</li>
<li><code>include!</code> : include the Rust expression in the given file</li>
<li><code>include_str!</code> : include the contents of the given file as a string</li>
<li><code>include_bin!</code> : include the contents of the given file as a binary blob</li>
<li><code>error!</code>, <code>warn!</code>, <code>info!</code>, <code>debug!</code> : provide diagnostic information.</li>
</ul>

<p>All of the above extensions are expressions with values.</p>

<h2 id="macros" class="section-header"><a href="#macros">4.1 Macros(宏)</a></h2>
<pre><code class="language-{.notrust">expr_macro_rules : "macro_rules" '!' ident '(' macro_rule * ')' ;
macro_rule : '(' matcher * ')' "=&gt;" '(' transcriber * ')' ';' ;
matcher : '(' matcher * ')' | '[' matcher * ']'
        | '{' matcher * '}' | '$' ident ':' ident
        | '$' '(' matcher * ')' sep_token? [ '*' | '+' ]
        | non_special_token ;
transcriber : '(' transcriber * ')' | '[' transcriber * ']'
            | '{' transcriber * '}' | '$' ident
            | '$' '(' transcriber * ')' sep_token? [ '*' | '+' ]
            | non_special_token ;</code></pre>

<p>User-defined syntax extensions are called "macros",
and the <code>macro_rules</code> syntax extension defines them.
Currently, user-defined macros can expand to expressions, statements, or items.</p>

<p>(A <code>sep_token</code> is any token other than <code>*</code> and <code>+</code>.
A <code>non_special_token</code> is any token other than a delimiter or <code>$</code>.)</p>

<p>The macro expander looks up macro invocations by name,
and tries each macro rule in turn.
It transcribes the first successful match.
Matching and transcription are closely related to each other,
and we will describe them together.</p>

<h3 id="macro-by-example" class="section-header"><a href="#macro-by-example">4.1.1 Macro By Example(宏例子)</a></h3>
<p>The macro expander matches and transcribes every token that does not begin with a <code>$</code> literally, including delimiters.
For parsing reasons, delimiters must be balanced, but they are otherwise not special.</p>

<p>In the matcher, <code>$</code> <em>name</em> <code>:</code> <em>designator</em> matches the nonterminal in the
Rust syntax named by <em>designator</em>. Valid designators are <code>item</code>, <code>block</code>,
<code>stmt</code>, <code>pat</code>, <code>expr</code>, <code>ty</code> (type), <code>ident</code>, <code>path</code>, <code>matchers</code> (lhs of the <code>=&gt;</code> in macro rules),
<code>tt</code> (rhs of the <code>=&gt;</code> in macro rules). In the transcriber, the designator is already known, and so only
the name of a matched nonterminal comes after the dollar sign.</p>

<p>In both the matcher and transcriber, the Kleene star-like operator indicates repetition.
The Kleene star operator consists of <code>$</code> and parens, optionally followed by a separator token, followed by <code>*</code> or <code>+</code>.
<code>*</code> means zero or more repetitions, <code>+</code> means at least one repetition.
The parens are not matched or transcribed.
On the matcher side, a name is bound to <em>all</em> of the names it
matches, in a structure that mimics the structure of the repetition
encountered on a successful match. The job of the transcriber is to sort that
structure out.</p>

<p>The rules for transcription of these repetitions are called "Macro By Example".
Essentially, one "layer" of repetition is discharged at a time, and all of
them must be discharged by the time a name is transcribed. Therefore,
<code>( $( $i:ident ),* ) =&gt; ( $i )</code> is an invalid macro, but
<code>( $( $i:ident ),* ) =&gt; ( $( $i:ident ),*  )</code> is acceptable (if trivial).</p>

<p>When Macro By Example encounters a repetition, it examines all of the <code>$</code>
<em>name</em> s that occur in its body. At the "current layer", they all must repeat
the same number of times, so
<code>( $( $i:ident ),* ; $( $j:ident ),* ) =&gt; ( $( ($i,$j) ),* )</code> is valid if
given the argument <code>(a,b,c ; d,e,f)</code>, but not <code>(a,b,c ; d,e)</code>. The repetition
walks through the choices at that layer in lockstep, so the former input
transcribes to <code>( (a,d), (b,e), (c,f) )</code>.</p>

<p>Nested repetitions are allowed.</p>

<h3 id="parsing-limitations" class="section-header"><a href="#parsing-limitations">4.1.2 Parsing limitations(解析限制)</a></h3>
<p>The parser used by the macro system is reasonably powerful, but the parsing of
Rust syntax is restricted in two ways:</p>

<ol>
<li>The parser will always parse as much as possible. If it attempts to match
<code>$i:expr [ , ]</code> against <code>8 [ , ]</code>, it will attempt to parse <code>i</code> as an array
index operation and fail. Adding a separator can solve this problem.</li>
<li>The parser must have eliminated all ambiguity by the time it reaches a <code>$</code> <em>name</em> <code>:</code> <em>designator</em>.
This requirement most often affects name-designator pairs when they occur at the beginning of, or immediately after, a <code>$(...)*</code>; requiring a distinctive token in front can solve the problem.</li>
</ol>

<h2 id="syntax-extensions-useful-for-the-macro-author" class="section-header"><a href="#syntax-extensions-useful-for-the-macro-author">4.2 Syntax extensions useful for the macro author(宏撰写有用的扩展语法)</a></h2>
<ul>
<li><code>log_syntax!</code> : print out the arguments at compile time</li>
<li><code>trace_macros!</code> : supply <code>true</code> or <code>false</code> to enable or disable macro expansion logging</li>
<li><code>stringify!</code> : turn the identifier argument into a string literal</li>
<li><code>concat!</code> : concatenates a comma-separated list of literals</li>
<li><code>concat_idents!</code> : create a new identifier by concatenating the arguments</li>
</ul>

<h1 id="crates-and-source-files" class="section-header"><a href="#crates-and-source-files">5 Crates and source files(Crates和源代码)</a></h1>
<p>Rust is a <em>compiled</em> language.
Its semantics obey a <em>phase distinction</em> between compile-time and run-time.
Those semantic rules that have a <em>static interpretation</em> govern 
the success or failure of compilation.
We refer to these rules as "static semantics".
Semantic rules called "dynamic semantics" govern the behavior of 
programs at run-time.
A program that fails to compile due to violation of a compile-time rule 
has no defined dynamic semantics; the compiler should halt with an error
 report, and produce no executable artifact.</p>
注意:有关文件源代码和模块层次定义的细节,在Tutorial 18 Crates and the module system说明的更加详细<a href=http://static.rust-lang.org/doc/master/tutorial.html#crates-and-the-module-system target=_blank>The Rust Language Tutorial</a><br>
Rust 是一种编译性语言.它的语义根据编译和运行阶段而有所分别.<br/>
这些语义规则在编译时有静态解释要么成功要么失败.<br>
语义规则称为"动态语义"是程序在运行时的产生的行为<br>
一个程序在编译时失败是因为违反了编译时没有定义动态语义的规则.<br>
编译器会停止给出错误报告，而不产生可执行工件.
<p>The compilation model centres on artifacts called <em>crates</em>.
Each compilation processes a single crate in source form, and if successful,
produces a single crate in binary form: either an executable or a
library.<sup id="fnref2"><a href="#fn2" rel="footnote">2</a></sup></p>

工件编译模型中心是crates.每个编译处理单一源代码形式的crate,如果成功,生成单一create的二进制形式:<br>
一个可执行文件或者一个库<br>
<p>A <em>crate</em> is a unit of compilation and linking, as well as versioning, distribution and runtime loading.
A crate contains a <em>tree</em> of nested <a href="#modules">module</a>
 scopes.
The top level of this tree is a module that is anonymous (from the point
 of view of paths within the module) and any item within a crate has a 
canonical <a href="#paths">module path</a> denoting its location within the crate's module tree.</p>
Crate 是编译和链接的单元,还有版本控制，分配和运行时加载.crate包含嵌套的模块范围树.<br>
这个树的最顶层是匿名模块(从这个模块的路径角度)并且在create内的所有项目都有一个经典的模块路径表示其在crate模块树内的位置.

<p>The Rust compiler is always invoked with a single source file as input, and always produces a single output crate.
The processing of that source file may result in other source files being loaded as modules.
Source files have the extension <code>.rs</code>.</p>
Rust编译器总是调用单一源文件作为输入,并且总是产生单一的输出create.被处理的源文件可以在其他源文件中作为模块调用.<br>
源文件具有扩展名.rs<br>
<p>A Rust source file describes a module, the name and
location of which — in the module tree of the current crate — are defined
from outside the source file: either by an explicit <code>mod_item</code> in
a referencing source file, or by the name of the crate itself.</p>
一个Rust源文件描述一个模块的名字和在当前crate模块树里的位置.crate通过外部源文件定义:<br>
要么是在引用源文件通过显式的mod_item或者是crate的名字.
<p>Each source file contains a sequence of zero or more <code>item</code> definitions,
and may optionally begin with any number of <code>attributes</code> that apply to the containing module.
Attributes on the anonymous crate module define important metadata that influences
the behavior of the compiler.</p>
每个源文件包含一系列0或多个项目定义.可选的开始任何数目的属性用于包含的模块.匿名crate模块的属性定义重要的元数据，<br>
可以影响编译器的行为.
<pre class="rust "><span class="comment">// Crate ID
</span><span class="attribute">#<span class="op">!</span>[<span class="ident">crate_id</span> <span class="op">=</span> <span class="string">"projx#2.5"</span>]</span><span class="comment">

// Additional metadata attributes
</span><span class="attribute">#<span class="op">!</span>[<span class="ident">desc</span> <span class="op">=</span> <span class="string">"Project X"</span>]</span>
<span class="attribute">#<span class="op">!</span>[<span class="ident">license</span> <span class="op">=</span> <span class="string">"BSD"</span>]</span>
<span class="attribute">#<span class="op">!</span>[<span class="ident">comment</span> <span class="op">=</span> <span class="string">"This is a comment on Project X."</span>]</span><span class="comment">

// Specify the output type
</span><span class="attribute">#<span class="op">!</span>[<span class="ident">crate_type</span> <span class="op">=</span> <span class="string">"lib"</span>]</span><span class="comment">

// Turn on a warning
</span><span class="attribute">#<span class="op">!</span>[<span class="ident">warn</span>(<span class="ident">non_camel_case_types</span>)]</span>
</pre>

<p>A crate that contains a <code>main</code> function can be compiled to an executable.
If a <code>main</code> function is present, its return type must be <a href="#primitive-types"><code>unit</code></a> and it must take no arguments.</p>
一个create包含 main 函数可以编译撑可执行文件.如果 main函数出现 它的返回值必须是unit类型，并且没有参数.
<h1 id="items-and-attributes" class="section-header"><a href="#items-and-attributes">6 Items and attributes(项目和属性)</a></h1>
<p>Crates contain <a href="#items">items</a>,
each of which may have some number of <a href="#attributes">attributes</a> attached to it.</p>
Crate包含项目，每个项目可以有一些数目的属性关联。
<h2 id="items" class="section-header"><a href="#items">6.1 Items(项目)</a></h2>
<pre><code class="language-{.notrust">item : mod_item | fn_item | type_item | struct_item | enum_item
     | static_item | trait_item | impl_item | extern_block ;</code></pre>

<p>An <em>item</em> is a component of a crate; some module items can be defined in crate
files, but most are defined in source files. Items are organized within a
crate by a nested set of <a href="#modules">modules</a>. Every crate has a single
"outermost" anonymous module; all further items within the crate have
<a href="#paths">paths</a> within the module tree of the crate.</p>
项目是crate的组件;一些模块项目可以在crate文件中定义.但是大多数是定义在源文件中.项目在crate里被组织嵌套的模块<br>
每个crate有单一的最外面的匿名模块.所有更多的crate里的项目在crate模块树里有路径.
<p>Items are entirely determined at compile-time, generally remain fixed during
execution, and may reside in read-only memory.</p>
项目全部实在编译时确定的。一般在执行时保持固定,也许保存在只读内存里.
<p>There are several kinds of item:</p>
有数种种类的项目
<ul>
<li><a href="#modules">modules(模块)</a></li>
<li><a href="#functions">functions(函数)</a></li>
<li><a href="#type-definitions">type definitions(类型声明)</a></li>
<li><a href="#structures">structures(结构)</a></li>
<li><a href="#enumerations">enumerations(枚举)</a></li>
<li><a href="#static-items">static items(静态项目)</a></li>
<li><a href="#traits">traits(特性或结构)</a></li>
<li><a href="#implementations">implementations(实现)</a></li>
</ul>

<p>Some items form an implicit scope for the declaration of sub-items. In other
words, within a function or module, declarations of items can (in many cases)
be mixed with the statements, control blocks, and similar artifacts that
otherwise compose the item body. The meaning of these scoped items is the same
as if the item was declared outside the scope — it is still a static item —
except that the item's <em>path name</em> within the module namespace is qualified by
the name of the enclosing item, or is private to the enclosing item (in the
case of functions).
The grammar specifies the exact locations in which sub-item declarations may appear.</p>
一些项目对子项目的申明形成隐式范围.换句话说,在函数或者模块里,声明项目(大多数情况下)是混合语句,控制块<br>
以及其他组合项目体的类似工件.这意味着这些范围的项目和这个范围以外声明的项目一样-它可以是一个静态项目除非项目的
路径名在其模块命名空间被封闭的项目修饰或者是私有的封闭项目(比如函数)
<h3 id="type-parameters" class="section-header"><a href="#type-parameters">6.1.1 Type Parameters(类型参数)</a></h3>
<p>All items except modules may be <em>parameterized</em> by type. Type parameters are
given as a comma-separated list of identifiers enclosed in angle brackets
(<code>&lt;...&gt;</code>), after the name of the item and before its definition.
The type parameters of an item are considered "part of the name", not part of the type of the item.
A referencing <a href="#paths">path</a> must (in principle) provide type
 arguments as a list of comma-separated types enclosed within angle 
brackets, in order to refer to the type-parameterized item.
In practice, the type-inference system can usually infer such argument 
types from context.
There are no general type-parametric types, only type-parametric items.
That is, Rust has no notion of type abstraction: there are no 
first-class "forall" types.</p>
所有项目除了模块(mod)之外都可以被类型参数化.类型参数化是项目名称之后，在开始定义之前，在封闭的尖括号内给出用逗号隔开的标识列表.
项目的类型参数也被认为是"名字的部分",而不是项目类型的部分.<br>
一个引用路径(在原则上)必须提供类型实际参数在封闭的尖括号内逗号分开的列表,为了参考类型参数化的项目.<br>
在实际中,类型推理系统可以从上下文中推断出实际参数的类型.没有泛性的类型参数化类型,只有类型参数化项目.<br>
这是因为,Rust没有类型抽象的符号：没有first-class 对所有的类型.
<h3 id="modules" class="section-header"><a href="#modules">6.1.2 Modules(模块)</a></h3>
<pre><code class="language-{.notrust">mod_item : "mod" ident ( ';' | '{' mod '}' );
mod : [ view_item | item ] * ;</code></pre>

<p>A module is a container for zero or more <a href="#view-items">view items</a> and zero or
more <a href="#items">items</a>. The view items manage the visibility of the items
defined within the module, as well as the visibility of names from outside the
module when referenced from inside the module.</p>
一个模块包括零个或者多个可见性项目和零个或多个项目.可见性项目管理项目在被定义模块内的可见性，<br>
以及从模块外部从一个项目类来引用时的可见性.
<p>A <em>module item</em> is a module, surrounded in braces, named, and prefixed with
the keyword <code>mod</code>. A module item introduces a new, named module into the tree
of modules making up a crate. Modules can nest arbitrarily.</p>
一个模块项目是一个模块被命名的花括号围绕，请且前缀使用关键词mod.一个模块项目引进一个新的命名的模块道组成crate的模块树内.
模块可以任意嵌套.
<p>An example of a module:</p>
<pre class="rust "><span class="kw">mod</span> <span class="ident">math</span> {
    <span class="kw">type</span> <span class="ident">Complex</span> <span class="op">=</span> (<span class="ident">f64</span>, <span class="ident">f64</span>);
    <span class="kw">fn</span> <span class="ident">sin</span>(<span class="ident">f</span>: <span class="ident">f64</span>) <span class="op">-&gt;</span> <span class="ident">f64</span> {<span class="comment">
        /* ... */
    </span>}
    <span class="kw">fn</span> <span class="ident">cos</span>(<span class="ident">f</span>: <span class="ident">f64</span>) <span class="op">-&gt;</span> <span class="ident">f64</span> {<span class="comment">
        /* ... */
    </span>}
    <span class="kw">fn</span> <span class="ident">tan</span>(<span class="ident">f</span>: <span class="ident">f64</span>) <span class="op">-&gt;</span> <span class="ident">f64</span> {<span class="comment">
        /* ... */
    </span>}
}
</pre>

<p>Modules and types share the same namespace.
Declaring a named type that has the same name as a module in scope is forbidden:
that is, a type definition, trait, struct, enumeration, or type parameter
can't shadow the name of a module in scope, or vice versa.</p>
模块和类型共享同一命名空间<br>
在范围内声明一个命名的类型和模块同名将会被禁止:这就是说类型定义，trait,结构,枚举或者类型参数不能使用范围内模块的影子名字,反之亦然<br>
<p>A module without a body is loaded from an external file, by default with the same
name as the module, plus the <code>.rs</code> extension.
When a nested submodule is loaded from an external file,
it is loaded from a subdirectory path that mirrors the module hierarchy.</p>
一个模块没有主体将会从外部文件载入,默认是和模块同样的名字后缀位.rs.<br>
当一个嵌套的子模块从外部同模块层次镜像的子目录载入,
<pre class="rust "><span class="comment">// Load the `vec` module from `vec.rs`
</span><span class="kw">mod</span> <span class="ident">vec</span>;

<span class="kw">mod</span> <span class="ident">task</span> {<span class="comment">
    // Load the `local_data` module from `task/local_data.rs`
    </span><span class="kw">mod</span> <span class="ident">local_data</span>;
}
</pre>

<p>The directories and files used for loading external file modules can be influenced
with the <code>path</code> attribute.</p>
用于载入外部文件模块的目录和文件可以用path属性来影响.
<pre class="rust "><span class="attribute">#[<span class="ident">path</span> <span class="op">=</span> <span class="string">"task_files"</span>]</span>
<span class="kw">mod</span> <span class="ident">task</span> {<span class="comment">
    // Load the `local_data` module from `task_files/tls.rs`
    </span><span class="attribute">#[<span class="ident">path</span> <span class="op">=</span> <span class="string">"tls.rs"</span>]</span>
    <span class="kw">mod</span> <span class="ident">local_data</span>;
}
</pre>

<h4 id="view-items" class="section-header"><a href="#view-items">6.1.2.1 View items(可见性项目)</a></h4>
<pre><code class="language-{.notrust">view_item : extern_crate_decl | use_decl ;</code></pre>

<p>A view item manages the namespace of a module.
View items do not define new items, but rather, simply change other items' visibility.
There are several kinds of view item:</p>
可见性项目管理模块的命名空间。可见性项目没有定义新的项目,但是简单的改变其他项目的可见性.有集中类型的可见性项目:
<ul>
<li><a href="#extern-crate-declarations"><code>extern crate</code> declarations</a></li>
<li><a href="#use-declarations"><code>use</code> declarations</a></li>
</ul>

<h5 id="extern-crate-declarations" class="section-header"><a href="#extern-crate-declarations">6.1.2.1.1 Extern crate declarations(外部crate声明)</a></h5>
<pre><code class="language-{.notrust">extern_crate_decl : "extern" "crate" ident [ '(' link_attrs ')' ] ? [ '=' string_lit ] ? ;
link_attrs : link_attr [ ',' link_attrs ] + ;
link_attr : ident '=' literal ;</code></pre>

<p>An <em><code>extern crate</code> declaration</em> specifies a dependency on an external crate.
The external crate is then bound into the declaring scope as the <code>ident</code> provided
in the <code>extern_crate_decl</code>.</p>
extern crate声明制定外部crate的依赖.外部crate绑定到extern_crate_decl声明标识.
<p>The external crate is resolved to a specific <code>soname</code> at compile time, and a
runtime linkage requirement to that <code>soname</code> is passed to the linker for
loading at runtime.  The <code>soname</code> is resolved at compile time by scanning the
compiler's library path and matching the optional <code>crateid</code> provided as a string literal
against the <code>crateid</code> attributes that were declared on the external crate when
it was compiled.  If no <code>crateid</code> is provided, a default <code>name</code> attribute is
assumed, equal to the <code>ident</code> given in the <code>extern_crate_decl</code>.</p>

 objdump libx.so.1.3 -p | grep SONAME

 外部crate解决编译时间特定共享库的soname,以及为了运行时载入要求的soname传递到链接程序.<br>
 soname在编译时解决扫描编译器的库路径以及匹配可选的crateid，crateid属性是由声明外部crate时creatid属性提供的字符串文字.
如果没有crateid,默认的名字属性就被假定等于extern_crate_decl声明所给的标识.
<p>Four examples of <code>extern crate</code> declarations:</p>
<pre class="rust "><span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">pcre</span>;

<span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">std</span>;<span class="comment"> // equivalent to: extern crate std = "std";

</span><span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">ruststd</span> <span class="op">=</span> <span class="string">"std"</span>;<span class="comment"> // linking to 'std' under another name

</span><span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">foo</span> <span class="op">=</span> <span class="string">"some/where/rust-foo#foo:1.0"</span>;<span class="comment"> // a full crate ID for external tools
</span></pre>

<h5 id="use-declarations" class="section-header"><a href="#use-declarations">6.1.2.1.2 Use declarations(use 声明)</a></h5>
<pre><code class="language-{.notrust">use_decl : "pub" ? "use" ident [ '=' path
                          | "::" path_glob ] ;

path_glob : ident [ "::" path_glob ] ?
          | '*'
          | '{' ident [ ',' ident ] * '}' ;</code></pre>

<p>A <em>use declaration</em> creates one or more local name bindings synonymous
with some other <a href="#paths">path</a>.
Usually a <code>use</code> declaration is used to shorten the path required to refer to a
module item. These declarations may appear at the top of <a href="#modules">modules</a> and
<a href="#blocks">blocks</a>.</p>

<p><em>Note</em>: Unlike in many languages,
<code>use</code> declarations in Rust do <em>not</em> declare linkage dependency with external crates.
Rather, <a href="#extern-crate-declarations"><code>extern crate</code> declarations</a> declare linkage dependencies.</p>
说明:不想其他大多数语言,Rust的use声明符并不声明一个外部crate链接依赖.
<p>Use declarations support a number of convenient shortcuts:</p>
use 声明符支持一些快捷方式.
<ul>
<li>Rebinding the target name as a new local name, using the syntax <code>use x = p::q::r;</code>.</li>
重新绑定目标名字位一个新的本地名字，使用语法 use x =p::q::r
<li>Simultaneously binding a list of paths differing only in their final element,
using the glob-like brace syntax <code>use a::b::{c,d,e,f};</code></li>
同时绑定列举路径不同仅在它们最后的元素,使用glob类似规则的花括号语法: use a::b::{c,d,e,f}.
<li>Binding all paths matching a given prefix, using the asterisk wildcard syntax <code>use a::b::*;</code></li>
绑定所有的路径匹配给定的前缀，使用星号通配符语法
</ul>

<p>An example of <code>use</code> declarations:</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">iter</span>::<span class="ident">range_step</span>;
<span class="kw">use</span> <span class="ident">std</span>::<span class="ident">option</span>::{<span class="prelude-val">Some</span>, <span class="prelude-val">None</span>};


<span class="kw">fn</span> <span class="ident">main</span>() {<span class="comment">
    // Equivalent to 'std::iter::range_step(0, 10, 2);'
    </span><span class="ident">range_step</span>(<span class="number">0</span>, <span class="number">10</span>, <span class="number">2</span>);<span class="comment">

    // Equivalent to 'foo(~[std::option::Some(1.0), std::option::None]);'
    </span><span class="ident">foo</span>(<span class="kw-2">~</span>[<span class="prelude-val">Some</span>(<span class="number">1.0</span>), <span class="prelude-val">None</span>]);
}
</pre>

<p>Like items, <code>use</code> declarations are private to the containing module, by default.
Also like items, a <code>use</code> declaration can be public, if qualified by the <code>pub</code> keyword.
Such a <code>use</code> declaration serves to <em>re-export</em> a name.
A public <code>use</code> declaration can therefore <em>redirect</em> some public name to a different target definition:
even a definition with a private canonical path, inside a different module.
If a sequence of such redirections form a cycle or cannot be resolved unambiguously,
they represent a compile-time error.</p>
如同项目(item),默认use 声明符号对包含其的模块也是私有的private.同样类似项目 use声明符号也可以是公开的public,如果修饰符是pub关键字<br>
这样一个use声明用于重新输出一个名字.
一个公众的public use声明重新定义一些公开名字到一个不同的目标定义:甚至定义在一些不同模块私有的规范路径.
如果这样的重定向序列形成了一个循环或者不能明白的解析，将产生一个编译错误.
<p>An example of re-exporting:</p>
<pre class="rust "><span class="kw">mod</span> <span class="ident">quux</span> {
    <span class="kw">pub</span> <span class="kw">use</span> <span class="ident">quux</span>::<span class="ident">foo</span>::<span class="op">*</span>;

    <span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">foo</span> {
        <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">bar</span>() { }
        <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">baz</span>() { }
    }
}
</pre>

<p>In this example, the module <code>quux</code> re-exports all of the public names defined in <code>foo</code>.</p>

<p>Also note that the paths contained in <code>use</code> items are relative to the crate root.
So, in the previous example, the <code>use</code> refers to <code>quux::foo::*</code>, and not simply to <code>foo::*</code>.
This also means that top-level module declarations should be at the crate root if direct usage
of the declared modules within <code>use</code> items is desired.  It is also possible to use <code>self</code> and <code>super</code>
at the beginning of a <code>use</code> item to refer to the current and direct parent modules respectively.
All rules regarding accessing declared modules in <code>use</code> declarations applies to both module declarations
and <code>extern crate</code> declarations.</p>
需要说明的是包含在use项目的路径是相对于crate root的.因此，在前面的例子里,use 指向quux::foo::*而不是简单的指向foo::*.
这以为这最顶级的模型声明在crate root,如果在use项目直接使用声明模块.也可以使用self和super在use 项目开始的地方标识参考标识母项模块。<br>
use声明所有的声明访问模块的规则也可以用于模块声明以及extern crate声明中。
<p>An example of what will and will not work for <code>use</code> items:</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">foo</span>::<span class="ident">native</span>::<span class="ident">start</span>;<span class="comment">  // good: foo is at the root of the crate
</span><span class="kw">use</span> <span class="ident">foo</span>::<span class="ident">baz</span>::<span class="ident">foobaz</span>;<span class="comment">    // good: foo is at the root of the crate

</span><span class="kw">mod</span> <span class="ident">foo</span> {
    <span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">native</span>;

    <span class="kw">use</span> <span class="ident">foo</span>::<span class="ident">native</span>::<span class="ident">start</span>;<span class="comment"> // good: foo is at crate root
//  use native::start;      // bad:  native is not at the crate root
    </span><span class="kw">use</span> <span class="self">self</span>::<span class="ident">baz</span>::<span class="ident">foobaz</span>;<span class="comment">  // good: self refers to module 'foo'
    </span><span class="kw">use</span> <span class="ident">foo</span>::<span class="ident">bar</span>::<span class="ident">foobar</span>;<span class="comment">   // good: foo is at crate root

    </span><span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">bar</span> {
        <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">foobar</span>() { }
    }

    <span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">baz</span> {
        <span class="kw">use</span> <span class="ident">super</span>::<span class="ident">bar</span>::<span class="ident">foobar</span>;<span class="comment"> // good: super refers to module 'foo'
        </span><span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">foobaz</span>() { }
    }
}

<span class="kw">fn</span> <span class="ident">main</span>() {}
</pre>

<h3 id="functions" class="section-header"><a href="#functions">6.1.3 Functions(函数)</a></h3>
<p>A <em>function item</em> defines a sequence of <a href="#statements">statements</a> and an optional final <a href="#expressions">expression</a>, along with a name and a set of parameters.
Functions are declared with the keyword <code>fn</code>.
Functions declare a set of <em>input</em> <a href="#memory-slots"><em>slots</em></a> as parameters, through which the caller passes arguments into the function, and an <em>output</em> <a href="#memory-slots"><em>slot</em></a> through which the function passes results back to the caller.</p>

<p>A function may also be copied into a first class <em>value</em>, in which case the
value has the corresponding <a href="#function-types"><em>function type</em></a>, and can be
used otherwise exactly as a function item (with a minor additional cost of
calling the function indirectly).</p>

<p>Every control path in a function logically ends with a <code>return</code> expression or a
diverging expression. If the outermost block of a function has a
value-producing expression in its final-expression position, that expression
is interpreted as an implicit <code>return</code> expression applied to the
final-expression.</p>

<p>An example of a function:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">add</span>(<span class="ident">x</span>: <span class="ident">int</span>, <span class="ident">y</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> <span class="ident">int</span> {
    <span class="kw">return</span> <span class="ident">x</span> <span class="op">+</span> <span class="ident">y</span>;
}
</pre>

<p>As with <code>let</code> bindings, function arguments are irrefutable patterns,
so any pattern that is valid in a let binding is also valid as an argument.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">first</span>((<span class="ident">value</span>, _): (<span class="ident">int</span>, <span class="ident">int</span>)) <span class="op">-&gt;</span> <span class="ident">int</span> { <span class="ident">value</span> }
</pre>

<h4 id="generic-functions" class="section-header"><a href="#generic-functions">6.1.3.1 Generic functions(泛性函数)</a></h4>
<p>A <em>generic function</em> allows one or more <em>parameterized types</em> to
appear in its signature. Each type parameter must be explicitly
declared, in an angle-bracket-enclosed, comma-separated list following
the function name.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">iter</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span>(<span class="ident">seq</span>: <span class="kw-2">&amp;</span>[<span class="ident">T</span>], <span class="ident">f</span>: <span class="op">|</span><span class="ident">T</span><span class="op">|</span>) {
    <span class="kw">for</span> <span class="ident">elt</span> <span class="kw">in</span> <span class="ident">seq</span>.<span class="ident">iter</span>() { <span class="ident">f</span>(<span class="ident">elt</span>); }
}
<span class="kw">fn</span> <span class="ident">map</span><span class="op">&lt;</span><span class="ident">T</span>, <span class="ident">U</span><span class="op">&gt;</span>(<span class="ident">seq</span>: <span class="kw-2">&amp;</span>[<span class="ident">T</span>], <span class="ident">f</span>: <span class="op">|</span><span class="ident">T</span><span class="op">|</span> <span class="op">-&gt;</span> <span class="ident">U</span>) <span class="op">-&gt;</span> <span class="kw-2">~</span>[<span class="ident">U</span>] {
    <span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">acc</span> <span class="op">=</span> <span class="kw-2">~</span>[];
    <span class="kw">for</span> <span class="ident">elt</span> <span class="kw">in</span> <span class="ident">seq</span>.<span class="ident">iter</span>() { <span class="ident">acc</span>.<span class="ident">push</span>(<span class="ident">f</span>(<span class="ident">elt</span>)); }
    <span class="ident">acc</span>
}
</pre>

<p>Inside the function signature and body, the name of the type parameter
can be used as a type name.</p>

<p>When a generic function is referenced, its type is instantiated based
on the context of the reference. For example, calling the <code>iter</code>
function defined above on <code>[1, 2]</code> will instantiate type parameter <code>T</code>
with <code>int</code>, and require the closure parameter to have type
<code>fn(int)</code>.</p>

<p>The type parameters can also be explicitly supplied in a trailing
<a href="#paths">path</a> component after the function name. This might be necessary
if there is not sufficient context to determine the type parameters. For
example, <code>mem::size_of::&lt;u32&gt;() == 4</code>.</p>

<p>Since a parameter type is opaque to the generic function, the set of
operations that can be performed on it is limited. Values of parameter
type can only be moved, not copied.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">id</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span>(<span class="ident">x</span>: <span class="ident">T</span>) <span class="op">-&gt;</span> <span class="ident">T</span> { <span class="ident">x</span> }
</pre>

<p>Similarly, <a href="#traits">trait</a> bounds can be specified for type
parameters to allow methods with that trait to be called on values
of that type.</p>

<h4 id="unsafety" class="section-header"><a href="#unsafety">6.1.3.2 Unsafety(unsafety 不安全)</a></h4>
<p>Unsafe operations are those that potentially violate the memory-safety guarantees of Rust's static semantics.</p>
unsafe运算符是潜在的违反Rust的静态语义内存安全担保
<p>The following language level features cannot be used in the safe subset of Rust:</p>
下列语言级别功能不能用于Rust的安全子集:
<ul>
<li>Dereferencing a <a href="#pointer-types">raw pointer</a>.</li>
 解引用一个原始指针
<li>Calling an unsafe function (including an intrinsic or foreign function).</li>
调用一个unsafe函数(包括固有或者外部函数)
</ul>

<h5 id="unsafe-functions" class="section-header"><a href="#unsafe-functions">6.1.3.2.1 Unsafe functions(不安全函数)</a></h5>
<p>Unsafe functions are functions that are not safe in all contexts and/or for all possible inputs.
Such a function must be prefixed with the keyword <code>unsafe</code>.</p>

<h5 id="unsafe-blocks" class="section-header"><a href="#unsafe-blocks">6.1.3.2.2 Unsafe blocks(不安全块)</a></h5>
<p>A block of code can also be prefixed with the <code>unsafe</code> keyword, to permit calling <code>unsafe</code> functions
or dereferencing raw pointers within a safe function.</p>

<p>When a programmer has sufficient conviction that a sequence of potentially unsafe operations is
actually safe, they can encapsulate that sequence (taken as a whole) within an <code>unsafe</code> block. The
compiler will consider uses of such code safe, in the surrounding context.</p>

<p>Unsafe blocks are used to wrap foreign libraries, make direct use of hardware or implement features
not directly present in the language. For example, Rust provides the language features necessary to
implement memory-safe concurrency in the language but the implementation of tasks and message
passing is in the standard library.</p>

<p>Rust's type system is a conservative approximation of the dynamic safety requirements, so in some
cases there is a performance cost to using safe code.  For example, a doubly-linked list is not a
tree structure and can only be represented with managed or reference-counted pointers in safe code.
By using <code>unsafe</code> blocks to represent the reverse links as raw pointers, it can be implemented with
only owned pointers.</p>

<h5 id="behavior-considered-unsafe" class="section-header"><a href="#behavior-considered-unsafe">6.1.3.2.3 Behavior considered unsafe(认为不安全的行为)</a></h5>
<p>This is a list of behavior which is forbidden in all Rust code. Type checking provides the guarantee
that these issues are never caused by safe code. An <code>unsafe</code> block or function is responsible for
never invoking this behaviour or exposing an API making it possible for it to occur in safe code.</p>

<ul>
<li>Data races(数据竞争)</li>
<li>Dereferencing a null/dangling raw pointer(解引用null/悬空原始指针)</li>
<li>Mutating an immutable value/reference(修改不可变值/引用)</li>
<li>Reads of <a href="http://llvm.org/docs/LangRef.html#undefined-values">undef</a> (uninitialized) memory(读取未定义内存)</li>
<li>Breaking the <a href="http://llvm.org/docs/LangRef.html#pointer-aliasing-rules">pointer aliasing rules</a>
with raw pointers (a subset of the rules used by C)</li>
用原始指针(C里使用的部分规则)中断指针别名规则
<li>Invoking undefined behavior via compiler intrinsics:
通过编译器内在函数调用未定义行为
<ul>
<li>Indexing outside of the bounds of an object with <code>std::ptr::offset</code> (<code>offset</code> intrinsic), with
the exception of one byte past the end which is permitted.</li>
使用std::ptr::offset索引在边界之外的对象.
<li>Using <code>std::ptr::copy_nonoverlapping_memory</code> (<code>memcpy32</code>/<code>memcpy64</code> instrinsics) on
overlapping buffers</li>
</ul></li>
<li>Invalid values in primitive types, even in private fields/locals:

<ul>
<li>Dangling/null pointers in non-raw pointers, or slices</li>
<li>A value other than <code>false</code> (0) or <code>true</code> (1) in a <code>bool</code></li>
<li>A discriminant in an <code>enum</code> not included in the type definition</li>
<li>A value in a <code>char</code> which is a surrogate or above <code>char::MAX</code></li>
<li>non-UTF-8 byte sequences in a <code>str</code></li>
</ul></li>
</ul>

<h5 id="behaviour-not-considered-unsafe" class="section-header"><a href="#behaviour-not-considered-unsafe">6.1.3.2.4 Behaviour not considered unsafe(不认为是不安全的行为)</a></h5>
<p>This is a list of behaviour not considered <em>unsafe</em> in Rust terms, but that may be undesired.</p>

<ul>
<li>Deadlocks</li>
<li>Reading data from private fields (<code>std::repr</code>, <code>format!("{:?}", x)</code>)</li>
<li>Leaks due to reference count cycles, even in the global heap</li>
<li>Exiting without calling destructors</li>
<li>Sending signals</li>
<li>Accessing/modifying the file system</li>
<li>Unsigned integer overflow (well-defined as wrapping)</li>
<li>Signed integer overflow (well-defined as two's complement representation wrapping)</li>
</ul>

<h4 id="diverging-functions" class="section-header"><a href="#diverging-functions">6.1.3.3 Diverging functions(发散函数)</a></h4>
<p>A special kind of function can be declared with a <code>!</code> character where the
output slot type would normally be. For example:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">my_err</span>(<span class="ident">s</span>: <span class="kw-2">&amp;</span><span class="ident">str</span>) <span class="op">-&gt;</span> <span class="op">!</span> {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">s</span>);
    <span class="macro">fail</span><span class="macro">!</span>();
}
</pre>
一些函数可以在输出插槽声明是个!字符
<p>We call such functions "diverging" because they never return a value to the
caller. Every control path in a diverging function must end with a
<code>fail!()</code> or a call to another diverging function on every
control path. The <code>!</code> annotation does <em>not</em> denote a type. Rather, the result
type of a diverging function is a special type called $\bot$ ("bottom") that
unifies with any type. Rust has no syntax for $\bot$.</p>
我们说这些函数是“发散”是因为它们从不返回一个值给调用者.在发散函数里每个控制路径必须用fail!()结束<br>
或者在每个控制路径调用另外一个发散函数<br>!符号不表示一个类型.
<p>It might be necessary to declare a diverging function because as mentioned
previously, the typechecker checks that every control path in a function ends
with a <a href="#return-expressions"><code>return</code></a> or diverging expression. So, if <code>my_err</code>
were declared without the <code>!</code> annotation, the following code would not
typecheck:</p>
<pre class="rust ">
<span class="kw">fn</span> <span class="ident">f</span>(<span class="ident">i</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> <span class="ident">int</span> {
   <span class="kw">if</span> <span class="ident">i</span> <span class="op">==</span> <span class="number">42</span> {
     <span class="kw">return</span> <span class="number">42</span>;
   }
   <span class="kw">else</span> {
     <span class="ident">my_err</span>(<span class="string">"Bad number!"</span>);
   }
}
</pre>

<p>This will not compile without the <code>!</code> annotation on <code>my_err</code>,
since the <code>else</code> branch of the conditional in <code>f</code> does not return an <code>int</code>,
as required by the signature of <code>f</code>.
Adding the <code>!</code> annotation to <code>my_err</code> informs the typechecker that,
should control ever enter <code>my_err</code>, no further type judgments about <code>f</code> need to hold,
since control will never resume in any context that relies on those judgments.
Thus the return type on <code>f</code> only needs to reflect the <code>if</code> branch of the conditional.</p>

<h4 id="extern-functions" class="section-header"><a href="#extern-functions">6.1.3.4 Extern functions(外部函数)</a></h4>
<p>Extern functions are part of Rust's foreign function interface,
providing the opposite functionality to <a href="#external-blocks">external blocks</a>.
Whereas external blocks allow Rust code to call foreign code,
extern functions with bodies defined in Rust code <em>can be called by foreign
code</em>. They are defined in the same way as any other Rust function,
except that they have the <code>extern</code> modifier.</p>
<pre class="rust "><span class="comment">// Declares an extern fn, the ABI defaults to "C"
</span><span class="kw">extern</span> <span class="kw">fn</span> <span class="ident">new_vec</span>() <span class="op">-&gt;</span> <span class="kw-2">~</span>[<span class="ident">int</span>] { <span class="kw-2">~</span>[] }<span class="comment">

// Declares an extern fn with "stdcall" ABI
</span><span class="kw">extern</span> <span class="string">"stdcall"</span> <span class="kw">fn</span> <span class="ident">new_vec_stdcall</span>() <span class="op">-&gt;</span> <span class="kw-2">~</span>[<span class="ident">int</span>] { <span class="kw-2">~</span>[] }
</pre>

<p>Unlike normal functions, extern fns have an <code>extern "ABI" fn()</code>.
This is the same type as the functions declared in an extern
block.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">fptr</span>: <span class="kw">extern</span> <span class="string">"C"</span> <span class="kw">fn</span>() <span class="op">-&gt;</span> <span class="kw-2">~</span>[<span class="ident">int</span>] <span class="op">=</span> <span class="ident">new_vec</span>;
</pre>

<p>Extern functions may be called directly from Rust code as Rust uses large,
contiguous stack segments like C.</p>

<h3 id="type-definitions" class="section-header"><a href="#type-definitions">6.1.4 Type definitions(类型定义)</a></h3>
<p>A <em>type definition</em> defines a new name for an existing <a href="#types">type</a>. Type
definitions are declared with the keyword <code>type</code>. Every value has a single,
specific type; the type-specified aspects of a value include:</p>

<ul>
<li>Whether the value is composed of sub-values or is indivisible.</li>
<li>Whether the value represents textual or numerical information.</li>
<li>Whether the value represents integral or floating-point information.</li>
<li>The sequence of memory operations required to access the value.</li>
<li>The <a href="#type-kinds">kind</a> of the type.</li>
</ul>

<p>For example, the type <code>(u8, u8)</code> defines the set of immutable values that are composite pairs,
each containing two unsigned 8-bit integers accessed by pattern-matching and laid out in memory with the <code>x</code> component preceding the <code>y</code> component.</p>

<h3 id="structures" class="section-header"><a href="#structures">6.1.5 Structures(结构)</a></h3>
<p>A <em>structure</em> is a nominal <a href="#structure-types">structure type</a> defined with the keyword <code>struct</code>.</p>

<p>An example of a <code>struct</code> item and its use:</p>
<pre class="rust "><span class="kw">struct</span> <span class="ident">Point</span> {<span class="ident">x</span>: <span class="ident">int</span>, <span class="ident">y</span>: <span class="ident">int</span>}
<span class="kw">let</span> <span class="ident">p</span> <span class="op">=</span> <span class="ident">Point</span> {<span class="ident">x</span>: <span class="number">10</span>, <span class="ident">y</span>: <span class="number">11</span>};
<span class="kw">let</span> <span class="ident">px</span>: <span class="ident">int</span> <span class="op">=</span> <span class="ident">p</span>.<span class="ident">x</span>;
</pre>

<p>A <em>tuple structure</em> is a nominal <a href="#tuple-types">tuple type</a>, also defined with the keyword <code>struct</code>.
For example:</p>
<pre class="rust "><span class="kw">struct</span> <span class="ident">Point</span>(<span class="ident">int</span>, <span class="ident">int</span>);
<span class="kw">let</span> <span class="ident">p</span> <span class="op">=</span> <span class="ident">Point</span>(<span class="number">10</span>, <span class="number">11</span>);
<span class="kw">let</span> <span class="ident">px</span>: <span class="ident">int</span> <span class="op">=</span> <span class="kw">match</span> <span class="ident">p</span> { <span class="ident">Point</span>(<span class="ident">x</span>, _) <span class="op">=&gt;</span> <span class="ident">x</span> };
</pre>

<p>A <em>unit-like struct</em> is a structure without any fields, defined by leaving off the list of fields entirely.
Such types will have a single value, just like the <a href="#unit-and-boolean-literals">unit value <code>()</code></a> of the unit type.
For example:</p>
<pre class="rust "><span class="kw">struct</span> <span class="ident">Cookie</span>;
<span class="kw">let</span> <span class="ident">c</span> <span class="op">=</span> [<span class="ident">Cookie</span>, <span class="ident">Cookie</span>, <span class="ident">Cookie</span>, <span class="ident">Cookie</span>];
</pre>

<p>By using the <code>struct_inherit</code> feature gate, structures may use single inheritance. A Structure may only
inherit from a single other structure, called the <em>super-struct</em>. The inheriting structure (sub-struct)
acts as if all fields in the super-struct were present in the sub-struct. Fields declared in a sub-struct
must not have the same name as any field in any (transitive) super-struct. All fields (both declared
and inherited) must be specified in any initializers. Inheritance between structures does not give
subtyping or coercion. The super-struct and sub-struct must be defined in the same crate. The super-struct
must be declared using the <code>virtual</code> keyword.
For example:</p>
<pre class="rust "><span class="kw">virtual</span> <span class="kw">struct</span> <span class="ident">Sup</span> { <span class="ident">x</span>: <span class="ident">int</span> }
<span class="kw">struct</span> <span class="ident">Sub</span> : <span class="ident">Sup</span> { <span class="ident">y</span>: <span class="ident">int</span> }
<span class="kw">let</span> <span class="ident">s</span> <span class="op">=</span> <span class="ident">Sub</span> {<span class="ident">x</span>: <span class="number">10</span>, <span class="ident">y</span>: <span class="number">11</span>};
<span class="kw">let</span> <span class="ident">sx</span> <span class="op">=</span> <span class="ident">s</span>.<span class="ident">x</span>;
</pre>

<h3 id="enumerations" class="section-header"><a href="#enumerations">6.1.6 Enumerations(枚举)</a></h3>
<p>An <em>enumeration</em> is a simultaneous definition of a nominal <a href="#enumerated-types">enumerated type</a> as well as a set of <em>constructors</em>,
that can be used to create or pattern-match values of the corresponding enumerated type.</p>

<p>Enumerations are declared with the keyword <code>enum</code>.</p>

<p>An example of an <code>enum</code> item and its use:</p>
<pre class="rust "><span class="kw">enum</span> <span class="ident">Animal</span> {
  <span class="ident">Dog</span>,
  <span class="ident">Cat</span>
}

<span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">a</span>: <span class="ident">Animal</span> <span class="op">=</span> <span class="ident">Dog</span>;
<span class="ident">a</span> <span class="op">=</span> <span class="ident">Cat</span>;
</pre>

<p>Enumeration constructors can have either named or unnamed fields:</p>
<pre class="rust "><span class="kw">enum</span> <span class="ident">Animal</span> {
    <span class="ident">Dog</span> (<span class="kw-2">~</span><span class="ident">str</span>, <span class="ident">f64</span>),
    <span class="ident">Cat</span> { <span class="ident">name</span>: <span class="kw-2">~</span><span class="ident">str</span>, <span class="ident">weight</span>: <span class="ident">f64</span> }
}

<span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">a</span>: <span class="ident">Animal</span> <span class="op">=</span> <span class="ident">Dog</span>(<span class="string">"Cocoa"</span>.<span class="ident">to_owned</span>(), <span class="number">37.2</span>);
<span class="ident">a</span> <span class="op">=</span> <span class="ident">Cat</span>{ <span class="ident">name</span>: <span class="string">"Spotty"</span>.<span class="ident">to_owned</span>(), <span class="ident">weight</span>: <span class="number">2.7</span> };
</pre>

<p>In this example, <code>Cat</code> is a <em>struct-like enum variant</em>,
whereas <code>Dog</code> is simply called an enum variant.</p>

<h3 id="static-items" class="section-header"><a href="#static-items">6.1.7 Static items(静态项目)</a></h3>
<pre><code class="language-{.notrust">static_item : "static" ident ':' type '=' expr ';' ;</code></pre>

<p>A <em>static item</em> is a named <em>constant value</em> stored in the global data section of a crate.
Immutable static items are stored in the read-only data section.
The constant value bound to a static item is, like all constant values, evaluated at compile time.
Static items have the <code>static</code> lifetime, which outlives all other lifetimes in a Rust program.
Static items are declared with the <code>static</code> keyword.
A static item must have a <em>constant expression</em> giving its definition.</p>

<p>Static items must be explicitly typed.
The type may be <code>bool</code>, <code>char</code>, a number, or a type derived from those primitive types.
The derived types are references with the <code>static</code> lifetime,
fixed-size arrays, tuples, and structs.</p>
<pre class="rust "><span class="kw">static</span> <span class="ident">BIT1</span>: <span class="ident">uint</span> <span class="op">=</span> <span class="number">1</span> <span class="op">&lt;&lt;</span> <span class="number">0</span>;
<span class="kw">static</span> <span class="ident">BIT2</span>: <span class="ident">uint</span> <span class="op">=</span> <span class="number">1</span> <span class="op">&lt;&lt;</span> <span class="number">1</span>;

<span class="kw">static</span> <span class="ident">BITS</span>: [<span class="ident">uint</span>, ..<span class="number">2</span>] <span class="op">=</span> [<span class="ident">BIT1</span>, <span class="ident">BIT2</span>];
<span class="kw">static</span> <span class="ident">STRING</span>: <span class="kw-2">&amp;</span><span class="lifetime">'static</span> <span class="ident">str</span> <span class="op">=</span> <span class="string">"bitstring"</span>;

<span class="kw">struct</span> <span class="ident">BitsNStrings</span><span class="op">&lt;</span><span class="lifetime">'a</span><span class="op">&gt;</span> {
    <span class="ident">mybits</span>: [<span class="ident">uint</span>, ..<span class="number">2</span>],
    <span class="ident">mystring</span>: <span class="kw-2">&amp;</span><span class="lifetime">'a</span> <span class="ident">str</span>
}

<span class="kw">static</span> <span class="ident">bits_n_strings</span>: <span class="ident">BitsNStrings</span><span class="op">&lt;</span><span class="lifetime">'static</span><span class="op">&gt;</span> <span class="op">=</span> <span class="ident">BitsNStrings</span> {
    <span class="ident">mybits</span>: <span class="ident">BITS</span>,
    <span class="ident">mystring</span>: <span class="ident">STRING</span>
};
</pre>

<h4 id="mutable-statics" class="section-header"><a href="#mutable-statics">6.1.7.1 Mutable statics(可变静态)</a></h4>
<p>If a static item is declared with the <code>mut</code> keyword, then it is allowed to
be modified by the program. One of Rust's goals is to make concurrency bugs hard
to run into, and this is obviously a very large source of race conditions or
other bugs. For this reason, an <code>unsafe</code> block is required when either
reading or writing a mutable static variable. Care should be taken to ensure
that modifications to a mutable static are safe with respect to other tasks
running in the same process.</p>
如果一个静态项目用mut关键词声明,那么它是允许程序修改.
<p>Mutable statics are still very useful, however. They can be used with C
libraries and can also be bound from C libraries (in an <code>extern</code> block).</p>
<pre class="rust ">
<span class="kw">static</span> <span class="kw-2">mut</span> <span class="ident">LEVELS</span>: <span class="ident">uint</span> <span class="op">=</span> <span class="number">0</span>;<span class="comment">

// This violates the idea of no shared state, and this doesn't internally
// protect against races, so this function is `unsafe`
</span><span class="kw">unsafe</span> <span class="kw">fn</span> <span class="ident">bump_levels_unsafe1</span>() <span class="op">-&gt;</span> <span class="ident">uint</span> {
    <span class="kw">let</span> <span class="ident">ret</span> <span class="op">=</span> <span class="ident">LEVELS</span>;
    <span class="ident">LEVELS</span> <span class="op">+=</span> <span class="number">1</span>;
    <span class="kw">return</span> <span class="ident">ret</span>;
}<span class="comment">

// Assuming that we have an atomic_add function which returns the old value,
// this function is "safe" but the meaning of the return value may not be what
// callers expect, so it's still marked as `unsafe`
</span><span class="kw">unsafe</span> <span class="kw">fn</span> <span class="ident">bump_levels_unsafe2</span>() <span class="op">-&gt;</span> <span class="ident">uint</span> {
    <span class="kw">return</span> <span class="ident">atomic_add</span>(<span class="kw-2">&amp;</span><span class="kw-2">mut</span> <span class="ident">LEVELS</span>, <span class="number">1</span>);
}
</pre>

<h3 id="traits" class="section-header"><a href="#traits">6.1.8 Traits(特性或接口)</a></h3>
<p>A <em>trait</em> describes a set of method types.</p>
trait 是描述一组方法类型.
<p>Traits can include default implementations of methods,
written in terms of some unknown <a href="#self-types"><code>self</code> type</a>;
the <code>self</code> type may either be completely unspecified,
or constrained by some other trait.</p>
traits可以包含默认的方法实现,使用未知的selft类型实现.
self可以是完全未指定的，或通过一些其他trait的限制。

<p>Traits are implemented for specific types through separate <a href="#implementations">implementations</a>.</p>
Traits对特定类型的实现是通过分离的<a href="#implementations">implementations</a>做到的.
<pre class="rust "><span class="kw">trait</span> <span class="ident">Shape</span> {
    <span class="kw">fn</span> <span class="ident">draw</span>(<span class="kw-2">&amp;</span><span class="self">self</span>, <span class="ident">Surface</span>);
    <span class="kw">fn</span> <span class="ident">bounding_box</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">BoundingBox</span>;
}
</pre>

<p>This defines a trait with two methods.
All values that have <a href="#implementations">implementations</a> of this trait in scope can have their <code>draw</code> and <code>bounding_box</code> methods called,
using <code>value.bounding_box()</code> <a href="#method-call-expressions">syntax</a>.</p>
这定义了一个有两个方法的trait,所有实现了这个trait的的值就有了draw和bounding_box方法可以调用,用语法:value.bounding_box().
<p>Type parameters can be specified for a trait to make it generic.
These appear after the trait name, using the same syntax used in <a href="#generic-functions">generic functions</a>.</p>
	trait的类型参数可以指定泛型的.在trait名字后面出现。这个名字的语法类似于<a href="#generic-functions">泛型函数</a>
<pre class="rust "><span class="kw">trait</span> <span class="ident">Seq</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> {
   <span class="kw">fn</span> <span class="ident">len</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">uint</span>;
   <span class="kw">fn</span> <span class="ident">elt_at</span>(<span class="kw-2">&amp;</span><span class="self">self</span>, <span class="ident">n</span>: <span class="ident">uint</span>) <span class="op">-&gt;</span> <span class="ident">T</span>;
   <span class="kw">fn</span> <span class="ident">iter</span>(<span class="kw-2">&amp;</span><span class="self">self</span>, <span class="op">|</span><span class="ident">T</span><span class="op">|</span>);
}
</pre>

<p>Generic functions may use traits as <em>bounds</em> on their type parameters.
This will have two effects: only types that have the trait may instantiate the parameter,
and within the generic function,
the methods of the trait can be called on values that have the parameter's type.
For example:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">draw_twice</span><span class="op">&lt;</span><span class="ident">T</span>: <span class="ident">Shape</span><span class="op">&gt;</span>(<span class="ident">surface</span>: <span class="ident">Surface</span>, <span class="ident">sh</span>: <span class="ident">T</span>) {
    <span class="ident">sh</span>.<span class="ident">draw</span>(<span class="ident">surface</span>);
    <span class="ident">sh</span>.<span class="ident">draw</span>(<span class="ident">surface</span>);
}
</pre>

<p>Traits also define an <a href="#object-types">object type</a> with the same name as the trait.
Values of this type are created by <a href="#type-cast-expressions">casting</a> pointer values
(pointing to a type for which an implementation of the given trait is in scope)
to pointers to the trait name, used as a type.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">myshape</span>: <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Shape</span><span class="op">&gt;</span> <span class="op">=</span> <span class="kw">box</span> <span class="ident">mycircle</span> <span class="kw">as</span> <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Shape</span><span class="op">&gt;</span>;
</pre>

<p>The resulting value is a box containing the value that was cast,
along with information that identifies the methods of the implementation that was used.
Values with a trait type can have <a href="#method-call-expressions">methods called</a> on them,
for any method in the trait,
and can be used to instantiate type parameters that are bounded by the trait.</p>

<p>Trait methods may be static,
which means that they lack a <code>self</code> argument.
This means that they can only be called with function call syntax (<code>f(x)</code>)
and not method call syntax (<code>obj.f()</code>).
The way to refer to the name of a static method is to qualify it with the trait name,
treating the trait name like a module.
For example:</p>
<pre class="rust "><span class="kw">trait</span> <span class="ident">Num</span> {
    <span class="kw">fn</span> <span class="ident">from_int</span>(<span class="ident">n</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> <span class="ident">Self</span>;
}
<span class="kw">impl</span> <span class="ident">Num</span> <span class="kw">for</span> <span class="ident">f64</span> {
    <span class="kw">fn</span> <span class="ident">from_int</span>(<span class="ident">n</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> <span class="ident">f64</span> { <span class="ident">n</span> <span class="kw">as</span> <span class="ident">f64</span> }
}
<span class="kw">let</span> <span class="ident">x</span>: <span class="ident">f64</span> <span class="op">=</span> <span class="ident">Num</span>::<span class="ident">from_int</span>(<span class="number">42</span>);
</pre>

<p>Traits may inherit from other traits. For example, in</p>
<pre class="rust "><span class="kw">trait</span> <span class="ident">Shape</span> { <span class="kw">fn</span> <span class="ident">area</span>() <span class="op">-&gt;</span> <span class="ident">f64</span>; }
<span class="kw">trait</span> <span class="ident">Circle</span> : <span class="ident">Shape</span> { <span class="kw">fn</span> <span class="ident">radius</span>() <span class="op">-&gt;</span> <span class="ident">f64</span>; }
</pre>

<p>the syntax <code>Circle : Shape</code> means that types that implement <code>Circle</code> must also have an implementation for <code>Shape</code>.
Multiple supertraits are separated by spaces, <code>trait Circle : Shape Eq { }</code>.
In an implementation of <code>Circle</code> for a given type <code>T</code>, methods can refer to <code>Shape</code> methods,
since the typechecker checks that any type with an implementation of <code>Circle</code> also has an implementation of <code>Shape</code>.</p>

<p>In type-parameterized functions,
methods of the supertrait may be called on values of subtrait-bound type parameters.
Referring to the previous example of <code>trait Circle : Shape</code>:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">radius_times_area</span><span class="op">&lt;</span><span class="ident">T</span>: <span class="ident">Circle</span><span class="op">&gt;</span>(<span class="ident">c</span>: <span class="ident">T</span>) <span class="op">-&gt;</span> <span class="ident">f64</span> {<span class="comment">
    // `c` is both a Circle and a Shape
    </span><span class="ident">c</span>.<span class="ident">radius</span>() <span class="op">*</span> <span class="ident">c</span>.<span class="ident">area</span>()
}
</pre>

<p>Likewise, supertrait methods may also be called on trait objects.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">mycircle</span>: <span class="ident">Circle</span> <span class="op">=</span> <span class="kw-2">~</span><span class="ident">mycircle</span> <span class="kw">as</span> <span class="kw-2">~</span><span class="ident">Circle</span>;
<span class="kw">let</span> <span class="ident">nonsense</span> <span class="op">=</span> <span class="ident">mycircle</span>.<span class="ident">radius</span>() <span class="op">*</span> <span class="ident">mycircle</span>.<span class="ident">area</span>();
</pre>

<h3 id="implementations" class="section-header"><a href="#implementations">6.1.9 Implementations(实现)</a></h3>
<p>An <em>implementation</em> is an item that implements a <a href="#traits">trait</a> for a specific type.</p>
实现是对特定类型实现trait的项目.
<p>Implementations are defined with the keyword <code>impl</code>.</p>
实现是通过关键词impl来定义的。
<pre class="rust "><span class="kw">struct</span> <span class="ident">Circle</span> {
    <span class="ident">radius</span>: <span class="ident">f64</span>,
    <span class="ident">center</span>: <span class="ident">Point</span>,
}

<span class="kw">impl</span> <span class="ident">Shape</span> <span class="kw">for</span> <span class="ident">Circle</span> {
    <span class="kw">fn</span> <span class="ident">draw</span>(<span class="kw-2">&amp;</span><span class="self">self</span>, <span class="ident">s</span>: <span class="ident">Surface</span>) { <span class="ident">do_draw_circle</span>(<span class="ident">s</span>, <span class="op">*</span><span class="self">self</span>); }
    <span class="kw">fn</span> <span class="ident">bounding_box</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">BoundingBox</span> {
        <span class="kw">let</span> <span class="ident">r</span> <span class="op">=</span> <span class="self">self</span>.<span class="ident">radius</span>;
        <span class="ident">BoundingBox</span>{<span class="ident">x</span>: <span class="self">self</span>.<span class="ident">center</span>.<span class="ident">x</span> <span class="op">-</span> <span class="ident">r</span>, <span class="ident">y</span>: <span class="self">self</span>.<span class="ident">center</span>.<span class="ident">y</span> <span class="op">-</span> <span class="ident">r</span>,
         <span class="ident">width</span>: <span class="number">2.0</span> <span class="op">*</span> <span class="ident">r</span>, <span class="ident">height</span>: <span class="number">2.0</span> <span class="op">*</span> <span class="ident">r</span>}
    }
}
</pre>

<p>It is possible to define an implementation without referring to a trait.
The methods in such an implementation can only be used
as direct calls on the values of the type that the implementation targets.
In such an implementation, the trait type and <code>for</code> after <code>impl</code> are omitted.
Such implementations are limited to nominal types (enums, structs),
and the implementation must appear in the same module or a sub-module as the <code>self</code> type.</p>
不用指向一个trait来定义实现也是可能的。这种对特定目标实现的方法只能直接用于这种类型的值<br>
这种实现中,trait类型和impl后面的for关键词都被忽略了<br>
这种执行一般只限于标称类型(枚举，结构),并且这种实现必须在同一个模块或者子模块中作为self类型.
<p>When a trait <em>is</em> specified in an <code>impl</code>,
all methods declared as part of the trait must be implemented,
with matching types and type parameter counts.</p>
当trait在impl中被指定的时候，所有trait声明的匹配的类型和类型参数个数的方法都必须实现.
<p>An implementation can take type parameters,
which can be different from the type parameters taken by the trait it implements.
Implementation parameters are written after the <code>impl</code> keyword.</p>
<pre class="rust "><span class="kw">impl</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> <span class="ident">Seq</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> <span class="kw">for</span> <span class="kw-2">~</span>[<span class="ident">T</span>] {<span class="comment">
   /* ... */
</span>}
<span class="kw">impl</span> <span class="ident">Seq</span><span class="op">&lt;</span><span class="ident">bool</span><span class="op">&gt;</span> <span class="kw">for</span> <span class="ident">u32</span> {<span class="comment">
   /* Treat the integer as a sequence of bits */
</span>}
</pre>

<h3 id="external-blocks" class="section-header"><a href="#external-blocks">6.1.10 External blocks(外部块)</a></h3>
<pre><code class="language-{.notrust">extern_block_item : "extern" '{' extern_block '}' ;
extern_block : [ foreign_fn ] * ;</code></pre>

<p>External blocks form the basis for Rust's foreign function interface.
Declarations in an external block describe symbols
in external, non-Rust libraries.</p>

<p>Functions within external blocks
are declared in the same way as other Rust functions,
with the exception that they may not have a body
and are instead terminated by a semicolon.</p>
<pre class="rust "><span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">libc</span>;
<span class="kw">use</span> <span class="ident">libc</span>::{<span class="ident">c_char</span>, <span class="ident">FILE</span>};

<span class="kw">extern</span> {
    <span class="kw">fn</span> <span class="ident">fopen</span>(<span class="ident">filename</span>: <span class="op">*</span><span class="ident">c_char</span>, <span class="ident">mode</span>: <span class="op">*</span><span class="ident">c_char</span>) <span class="op">-&gt;</span> <span class="op">*</span><span class="ident">FILE</span>;
}
</pre>

<p>Functions within external blocks may be called by Rust code,
just like functions defined in Rust.
The Rust compiler automatically translates
between the Rust ABI and the foreign ABI.</p>

<p>A number of <a href="#attributes">attributes</a> control the behavior of external
blocks.</p>

<p>By default external blocks assume that the library they are calling
uses the standard C "cdecl" ABI.  Other ABIs may be specified using
an <code>abi</code> string, as shown here:</p>
<pre class="rust "><span class="comment">// Interface to the Windows API
</span><span class="kw">extern</span> <span class="string">"stdcall"</span> { }
</pre>

<p>The <code>link</code> attribute allows the name of the library to be specified. When
specified the compiler will attempt to link against the native library of the
specified name.</p>
<pre class="rust "><span class="attribute">#[<span class="ident">link</span>(<span class="ident">name</span> <span class="op">=</span> <span class="string">"crypto"</span>)]</span>
<span class="kw">extern</span> { }
</pre>

<p>The type of a function declared in an extern block is <code>extern "abi" fn(A1,
..., An) -&gt; R</code>, where <code>A1...An</code> are the declared types of its arguments and
<code>R</code> is the declared return type.</p>

<h2 id="visibility-and-privacy" class="section-header"><a href="#visibility-and-privacy">6.2 Visibility and Privacy(可见性和隐私)</a></h2>
<p>These two terms are often used interchangeably, and what they are attempting to
convey is the answer to the question "Can this item be used at this location?"</p>
这两个术语(可见性和隐私)经常是可以互换的,它们都试图回答这样一个问题"这个项目可以在这个位置使用吗?"
<p>Rust's name resolution operates on a global hierarchy of namespaces. Each level
in the hierarchy can be thought of as some item. The items are one of those
mentioned above, but also include external crates. Declaring or defining a new
module can be thought of as inserting a new tree into the hierarchy at the
location of the definition.</p>
Rust 名字解析工作是在命名空间全局层次上操作.层次上的每一个级别可以认为是一些项目.
这些项目就是上面提到的那些项目之一,但同时包含外部crate.声明或者定义一个新的模块可以认为插入一个新的
树到在定义位置的层次里.
<p>To control whether interfaces can be used across modules, Rust checks each use
of an item to see whether it should be allowed or not. This is where privacy
warnings are generated, or otherwise "you used a private item of another module
and weren't allowed to."</p>
为了控制是否接口可以跨越模块使用,Rust检查每一个项目来确认该项目是允许或者不允许.
这就是私有警告产生的原因了,或者"你不允许使用另外一个模块的私有项目"
<p>By default, everything in rust is <em>private</em>, with one exception. Enum variants
in a <code>pub</code> enum are also public by default. You are allowed to alter this
default visibility with the <code>priv</code> keyword. When an item is declared as <code>pub</code>,
it can be thought of as being accessible to the outside world. For example:</p>
默认的,rust里所有的项目都是私有的(private),只有一个例外.枚举变量默认就是公开的(pub),你可以通过
改变默认的可见性使用priv关键词.当一个项目声明为pub,它就可以被认为是可以被外部世界访问的.
<pre class="rust "><span class="comment">// Declare a private struct
</span><span class="kw">struct</span> <span class="ident">Foo</span>;<span class="comment">

// Declare a public struct with a private field
</span><span class="kw">pub</span> <span class="kw">struct</span> <span class="ident">Bar</span> {
    <span class="ident">field</span>: <span class="ident">int</span>
}<span class="comment">

// Declare a public enum with two public variants
</span><span class="kw">pub</span> <span class="kw">enum</span> <span class="ident">State</span> {
    <span class="ident">PubliclyAccessibleState</span>,
    <span class="ident">PubliclyAccessibleState2</span>,
}
</pre>

<p>With the notion of an item being either public or private, Rust allows item
accesses in two cases:</p>
当一个项目符号要么是公开的public或者私有的private,Rust允许在两种情况可以访问项目
<ol>
<li>If an item is public, then it can be used externally through any of its
public ancestors.</li>
如果项目是公开的,它可以通过它的公开的祖先给外部访问。
<li>If an item is private, it may be accessed by the current module and its
descendants.</li>
如果项目是私有的,它可以被当前模块内和它的后裔访问。
</ol>

<p>These two cases are surprisingly powerful for creating module hierarchies
exposing public APIs while hiding internal implementation details. To help
explain, here's a few use cases and what they would entail.</p>
这两种情况在建立模块层次暴露公开的API同时隐藏实现细节尤其强大.
为了更好的理解,我们拿一些case来展示它们的含义.
<ul>
<li><p>A library developer needs to expose functionality to crates which link against
their library. As a consequence of the first case, this means that anything
which is usable externally must be <code>pub</code> from the root down to the destination
item. Any private item in the chain will disallow external accesses.</p></li>
一个库开发者必须给crate暴露功能以便crate可以链接到他们的库.作为第一个case的结果,
这意味着外部可用的所有东西都必须是pub的,从根部向下一直到目标项目.任何在这个链条上的
私有项目都会禁止外部的访问。
<li><p>A crate needs a global available "helper module" to itself, but it doesn't
want to expose the helper module as a public API. To accomplish this, the root
of the crate's hierarchy would have a private module which then internally has
a "public api". Because the entire crate is a descendant of the root, then the
entire local crate can access this private module through the second case.</p></li>
一个crate自身需要全局可用的"帮助模块",但它并不想暴露帮助模块作为公开的API。
为了做到这个要求,crate层次的根部必须有一个私有的模块其内部有公开的API。
由于整个crate是根的后裔,所以整个局部crate可以通过第二个case访问这个私有模块.
<li><p>When writing unit tests for a module, it's often a common idiom to have an
immediate child of the module to-be-tested named <code>mod test</code>. This module could
access any items of the parent module through the second case, meaning that
internal implementation details could also be seamlessly tested from the child
module.</p></li>
当写一个模块单元测试的时候，经常性的傻瓜方法就是立即写一个子模块用mod test来命名.
这个模块可以通过第二个case访问母模块的所有项目,这就意味着内部实现细节从子模块可以无缝测试
</ul>

<p>In the second case, it mentions that a private item "can be accessed" by the
current module and its descendants, but the exact meaning of accessing an item
depends on what the item is. Accessing a module, for example, would mean looking
inside of it (to import more items). On the other hand, accessing a function
would mean that it is invoked. Additionally, path expressions and import
statements are considered to access an item in the sense that the
import/expression is only valid if the destination is in the current visibility
scope.</p>
第二个case里,提到私有项目"可以被访问"被当前模块和它的后裔,但是更加准确的有关访问的意味着这要看
项目自身是什么类型的项目了.访问一个模块，举例,就意味着查看其内部(将导入更多的项目).换句话说,
访问一个函数意味着它可以被调用.另外,路径表达式和导入语句都被认为是同一个意思:目标项目必须在当前可见范围内
这样才是合法的.
<p>Here's an example of a program which exemplifies the three cases outlined above.</p>
这就是上面三个case的大纲例子程序.
<pre class="rust "><span class="comment">// This module is private, meaning that no external crate can access this
	//这个模块是私有的,意味着没有外部的crate可以访问这个模块.
// module. Because it is private at the root of this current crate, however, any
//因为在当前crate里它从root就是私有的,当然
// module in the crate may access any publicly visible item in this module.
//当前crate里的任何其他模块都可访问模块内公开(public)可见的项目.
</span><span class="kw">mod</span> <span class="ident">crate_helper_module</span> {<span class="comment">

    // This function can be used by anything in the current crate
    //这个函数可以被当前crate里其他任何内容使用
    </span><span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">crate_helper</span>() {}<span class="comment">

    // This function *cannot* be used by anything else in the crate. It is not
    // publicly visible outside of the `crate_helper_module`, so only this
    // current module and its descendants may access it.
    //这个函数*不能*被当前crate其他任何内容使用.在本模块crate_helper_module之外它是不公开的.
    //应此只有当前模块和本模块的后裔可以访问它.
    </span><span class="kw">fn</span> <span class="ident">implementation_detail</span>() {}
}<span class="comment">

// This function is "public to the root" meaning that it's available to external
// crates linking against this one.
//这个函数是root公开的,意味着它可以从外部crate连接到这里.
</span><span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">public_api</span>() {}<span class="comment">

// Similarly to 'public_api', this module is public so external crates may look
// inside of it.
//同上面的函数'public_api'相似，这个模块是公开的,所以外部的crate可以看到它的内部.
</span><span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">submodule</span> {
    <span class="kw">use</span> <span class="ident">crate_helper_module</span>;

    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">my_method</span>() {<span class="comment">
        // Any item in the local crate may invoke the helper module's public
        // interface through a combination of the two rules above.
        //局部create可以通过组合上面的个规则来调用helper模块的公开的接口,如下.
        </span><span class="ident">crate_helper_module</span>::<span class="ident">crate_helper</span>();
    }<span class="comment">

    // This function is hidden to any module which is not a descendant of
    // `submodule`
    //这个函数对任何模块都是不可见的，因为它不是任何子模块的后裔.
    </span><span class="kw">fn</span> <span class="ident">my_implementation</span>() {}

    <span class="attribute">#[<span class="ident">cfg</span>(<span class="ident">test</span>)]</span>
    <span class="kw">mod</span> <span class="ident">test</span> {

        <span class="attribute">#[<span class="ident">test</span>]</span>
        <span class="kw">fn</span> <span class="ident">test_my_implementation</span>() {<span class="comment">
            // Because this module is a descendant of `submodule`, it's allowed
            // to access private items inside of `submodule` without a privacy
            // violation.
            //因为这个模块是子模块的后裔,所以它就允许访问子模块内私有的项目而不会违反隐私。
            </span><span class="ident">super</span>::<span class="ident">my_implementation</span>();
        }
    }
}
</pre>

<p>For a rust program to pass the privacy checking pass, all paths must be valid
accesses given the two rules above. This includes all use statements,
expressions, types, etc.</p>
为了rust 程序可以通过隐私检查,所有的路径必须合法的访问符合上面2个规则.包括了所有的use语句,表达式，类型等等
<h3 id="re-exporting-and-visibility" class="section-header"><a href="#re-exporting-and-visibility">6.2.1 Re-exporting and Visibility(重新输出和可见性)</a></h3>
<p>Rust allows publicly re-exporting items through a <code>pub use</code> directive. Because
this is a public directive, this allows the item to be used in the current
module through the rules above. It essentially allows public access into the
re-exported item. For example, this program is valid:</p>
Rust允许使用pub use指示符公开的重新输出项目.因为这是公开的指示符,允许项目基于上述两个规则被用于当前模块.
它基本上允许公开的访问重新输出的项目.比如，这个程序是合法的.

<pre class="rust "><span class="kw">pub</span> <span class="kw">use</span> <span class="ident">api</span> <span class="op">=</span> <span class="self">self</span>::<span class="ident">implementation</span>;

<span class="kw">mod</span> <span class="ident">implementation</span> {
    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">f</span>() {}
}
</pre>

<p>This means that any external crate referencing <code>implementation::f</code> would receive
a privacy violation, while the path <code>api::f</code> would be allowed.</p>
这既是说任何外部的crate如果尝试引用<code>implementation::f</code>就会得到一个侵犯隐私的错误,
但如果用路径 <code>api::f</code>就允许了.
<p>When re-exporting a private item, it can be thought of as allowing the "privacy
chain" being short-circuited through the reexport instead of passing through the
namespace hierarchy as it normally would.</p>
当重新输出一个私有的项目,可以认为是建立一个隐私链条的快捷方式通过了正常的命名空间层次.
<h3 id="glob-imports-and-visibility" class="section-header"><a href="#glob-imports-and-visibility">6.2.2 Glob imports and Visibility(通配输入和可见性)</a></h3>
<p>Currently glob imports are considered an "experimental" language feature. For
sanity purpose along with helping the implementation, glob imports will only
import public items from their destination, not private items.</p>

<blockquote>
<p><strong>Note:</strong> This is subject to change, glob exports may be removed entirely or
they could possibly import private items for a privacy error to later be
issued if the item is used.</p>
</blockquote>

<h2 id="attributes" class="section-header"><a href="#attributes">6.3 Attributes(属性)</a></h2>
<pre><code class="language-{.notrust">attribute : '#' '!' ? '[' meta_item ']' ;
meta_item : ident [ '=' literal
                  | '(' meta_seq ')' ] ? ;
meta_seq : meta_item [ ',' meta_seq ]* ;</code></pre>

<p>Static entities in Rust — crates, modules and items — may have <em>attributes</em>
applied to them. Attributes in Rust are modeled on Attributes in ECMA-335,
with the syntax coming from ECMA-334 (C#). An attribute is a general,
free-form metadatum that is interpreted according to name, convention, and
language and compiler version. Attributes may appear as any of:</p>
Rust静态实体-crates,模型和项目-可以有属性用于它们.属性都是仿照属性是在ECMA-335，由ECMA-334（C＃）的语法.
属性就是一般,自由形式的元数据,根据名字,惯例,语言和编译器版本被解释.属性可以显示作为任意下列之一:
<ul>
<li>A single identifier, the attribute name</li>
单一标识,属性名字
<li>An identifier followed by the equals sign '=' and a literal, providing a
key/value pair</li>
一个标识跟着符号=和文字,提供一个key/value对
<li>An identifier followed by a parenthesized list of sub-attribute arguments</li>
一个标识跟着括号中子属性参数列表
</ul>

<p>Attributes with a bang ("!") after the hash ("#") apply to the item that the
attribute is declared within. Attributes that do not have a bang after the
hash apply to the item that follows the attribute.</p>
属性在符号#之后跟着一个!用于在属性内声明的项目.属性没有!在#符号之后用于属性跟随的项目.
<p>An example of attributes:</p>
<pre class="rust "><span class="comment">// General metadata applied to the enclosing module or crate.
</span><span class="attribute">#<span class="op">!</span>[<span class="ident">license</span> <span class="op">=</span> <span class="string">"BSD"</span>]</span><span class="comment">

// A function marked as a unit test
</span><span class="attribute">#[<span class="ident">test</span>]</span>
<span class="kw">fn</span> <span class="ident">test_foo</span>() {<span class="comment">
  /* ... */
</span>}<span class="comment">

// A conditionally-compiled module
</span><span class="attribute">#[<span class="ident">cfg</span>(<span class="ident">target_os</span><span class="op">=</span><span class="string">"linux"</span>)]</span>
<span class="kw">mod</span> <span class="ident">bar</span> {<span class="comment">
  /* ... */
</span>}<span class="comment">

// A lint attribute used to suppress a warning/error
</span><span class="attribute">#[<span class="ident">allow</span>(<span class="ident">non_camel_case_types</span>)]</span>
<span class="kw">type</span> <span class="ident">int8_t</span> <span class="op">=</span> <span class="ident">i8</span>;
</pre>

<blockquote>
<p><strong>Note:</strong> At some point in the future, the compiler will distinguish between
language-reserved and user-available attributes. Until then, there is
effectively no difference between an attribute handled by a loadable syntax
extension and the compiler.</p>
</blockquote>

<h3 id="crate-only-attributes" class="section-header"><a href="#crate-only-attributes">6.3.1 Crate-only attributes(Crate-仅有属性)</a></h3>
<ul>
<li><code>crate_id</code> - specify the this crate's crate ID.</li>
<li><code>crate_type</code> - see <a href="#linkage">linkage</a>.</li>
<li><code>feature</code> - see <a href="#compiler-features">compiler features</a>.</li>
<li><code>no_main</code> - disable emitting the <code>main</code> symbol. Useful when some other
object being linked to defines <code>main</code>.</li>
<li><code>no_start</code> - disable linking to the <code>native</code> crate, which specifies the
"start" language item.</li>
<li><code>no_std</code> - disable linking to the <code>std</code> crate.</li>
</ul>

<h3 id="module-only-attributes" class="section-header"><a href="#module-only-attributes">6.3.2 Module-only attributes</a></h3>
<ul>
<li><code>macro_escape</code> - macros defined in this module will be visible in the
module's parent, after this module has been included.</li>
<li><code>no_implicit_prelude</code> - disable injecting <code>use std::prelude::*</code> in this
module.</li>
<li><code>path</code> - specifies the file to load the module from. <code>#[path="foo.rs"] mod
bar;</code> is equivalent to <code>mod bar { /* contents of foo.rs */ }</code>. The path is
taken relative to the directory that the current module is in.</li>
</ul>

<h3 id="function-only-attributes" class="section-header"><a href="#function-only-attributes">6.3.3 Function-only attributes(函数仅有属性)</a></h3>
<ul>
<li><code>macro_registrar</code> - when using loadable syntax extensions, mark this
function as the registration point for the current crate's syntax
extensions.</li>
<li><code>main</code> - indicates that this function should be passed to the entry point,
rather than the function in the crate root named <code>main</code>.</li>
<li><code>start</code> - indicates that this function should be used as the entry point,
overriding the "start" language item.  See the "start" <a href="#language-items">language
item</a> for more details.</li>
</ul>

<h3 id="static-only-attributes" class="section-header"><a href="#static-only-attributes">6.3.4 Static-only attributes(静态仅有属性)</a></h3>
<ul>
<li><code>address_insignificant</code> - references to this static may alias with
references to other statics, potentially of unrelated type.</li>
<li><code>thread_local</code> - on a <code>static mut</code>, this signals that the value of this
static may change depending on the current thread. The exact consequences of
this are implementation-defined.</li>
</ul>

<h3 id="ffi-attributes" class="section-header"><a href="#ffi-attributes">6.3.5 FFI attributes(FFI属性)</a></h3>
<p>On an <code>extern</code> block, the following attributes are interpreted:</p>

<ul>
<li><code>link_args</code> - specify arguments to the linker, rather than just the library
name and type. This is feature gated and the exact behavior is
implementation-defined (due to variety of linker invocation syntax).</li>
<li><code>link</code> - indicate that a native library should be linked to for the
declarations in this block to be linked correctly. See <a href="#external-blocks">external
blocks</a></li>
</ul>

<p>On declarations inside an <code>extern</code> block, the following attributes are
interpreted:</p>

<ul>
<li><code>link_name</code> - the name of the symbol that this function or static should be
imported as.</li>
<li><code>linkage</code> - on a static, this specifies the <a href="http://llvm.org/docs/LangRef.html#linkage-types">linkage
type</a>.</li>
</ul>

<h3 id="miscellaneous-attributes" class="section-header"><a href="#miscellaneous-attributes">6.3.6 Miscellaneous attributes(杂项属性)</a></h3>
<ul>
<li><code>link_section</code> - on statics and functions, this specifies the section of the
object file that this item's contents will be placed into.</li>
<li><code>macro_export</code> - export a macro for cross-crate usage.</li>
<li><code>no_mangle</code> - on any item, do not apply the standard name mangling. Set the
symbol for this item to its identifier.</li>
<li><code>packed</code> - on structs or enums, eliminate any padding that would be used to
align fields.</li>
<li><code>repr</code> - on C-like enums, this sets the underlying type used for
representation. Useful for FFI. Takes one argument, which is the primitive
type this enum should be represented for, or <code>C</code>, which specifies that it
should be the default <code>enum</code> size of the C ABI for that platform. Note that
enum representation in C is undefined, and this may be incorrect when the C
code is compiled with certain flags.</li>
<li><code>simd</code> - on certain tuple structs, derive the arithmetic operators, which
lower to the target's SIMD instructions, if any.</li>
<li><code>static_assert</code> - on statics whose type is <code>bool</code>, terminates compilation
with an error if it is not initialized to <code>true</code>.</li>
<li><code>unsafe_destructor</code> - allow implementations of the "drop" language item
where the type it is implemented for does not implement the "send" language
item.</li>
<li><code>unsafe_no_drop_flag</code> - on structs, remove the flag that prevents
destructors from being run twice. Destructors might be run multiple times on
the same object with this attribute.</li>
</ul>

<h3 id="conditional-compilation" class="section-header"><a href="#conditional-compilation">6.3.7 Conditional compilation(条件编译)</a></h3>
<p>Sometimes one wants to have different compiler outputs from the same code,
depending on build target, such as targeted operating system, or to enable
release builds.</p>

<p>There are two kinds of configuration options, one that is either defined or not
(<code>#[cfg(foo)]</code>), and the other that contains a string that can be checked
against (<code>#[cfg(bar = "baz")]</code> (currently only compiler-defined configuration
options can have the latter form).</p>
<pre class="rust "><span class="comment">// The function is only included in the build when compiling for OSX
</span><span class="attribute">#[<span class="ident">cfg</span>(<span class="ident">target_os</span> <span class="op">=</span> <span class="string">"macos"</span>)]</span>
<span class="kw">fn</span> <span class="ident">macos_only</span>() {<span class="comment">
  // ...
</span>}<span class="comment">

// This function is only included when either foo or bar is defined
</span><span class="attribute">#[<span class="ident">cfg</span>(<span class="ident">foo</span>)]</span>
<span class="attribute">#[<span class="ident">cfg</span>(<span class="ident">bar</span>)]</span>
<span class="kw">fn</span> <span class="ident">needs_foo_or_bar</span>() {<span class="comment">
  // ...
</span>}<span class="comment">

// This function is only included when compiling for a unixish OS with a 32-bit
// architecture
</span><span class="attribute">#[<span class="ident">cfg</span>(<span class="ident">unix</span>, <span class="ident">target_word_size</span> <span class="op">=</span> <span class="string">"32"</span>)]</span>
<span class="kw">fn</span> <span class="ident">on_32bit_unix</span>() {<span class="comment">
  // ...
</span>}
</pre>

<p>This illustrates some conditional compilation can be achieved using the
<code>#[cfg(...)]</code> attribute. Note that <code>#[cfg(foo, bar)]</code> is a condition that needs
both <code>foo</code> and <code>bar</code> to be defined while <code>#[cfg(foo)] #[cfg(bar)]</code> only needs
one of <code>foo</code> and <code>bar</code> to be defined (this resembles in the disjunctive normal
form). Additionally, one can reverse a condition by enclosing it in a
<code>not(...)</code>, like e. g. <code>#[cfg(not(target_os = "win32"))]</code>.</p>

<p>The following configurations must be defined by the implementation:</p>

<ul>
<li><code>target_arch = "..."</code>. Target CPU architecture, such as <code>"x86"</code>, <code>"x86_64"</code>
<code>"mips"</code>, or <code>"arm"</code>.</li>
<li><code>target_endian = "..."</code>. Endianness of the target CPU, either <code>"little"</code> or
<code>"big"</code>.</li>
<li><code>target_family = "..."</code>. Operating system family of the target, e. g.
<code>"unix"</code> or <code>"windows"</code>. The value of this configuration option is defined as
a configuration itself, like <code>unix</code> or <code>windows</code>.</li>
<li><code>target_os = "..."</code>. Operating system of the target, examples include
<code>"win32"</code>, <code>"macos"</code>, <code>"linux"</code>, <code>"android"</code> or <code>"freebsd"</code>.</li>
<li><code>target_word_size = "..."</code>. Target word size in bits. This is set to <code>"32"</code>
for targets with 32-bit pointers, and likewise set to <code>"64"</code> for 64-bit
pointers.</li>
<li><code>unix</code>. See <code>target_family</code>.</li>
<li><code>windows</code>. See <code>target_family</code>.</li>
</ul>

<h3 id="lint-check-attributes" class="section-header"><a href="#lint-check-attributes">6.3.8 Lint check attributes(Lint检查属性)</a></h3>
<p>A lint check names a potentially undesirable coding pattern, such as
unreachable code or omitted documentation, for the static entity to
which the attribute applies.</p>

<p>For any lint check <code>C</code>:</p>

<ul>
<li><code>warn(C)</code> warns about violations of <code>C</code> but continues compilation,</li>
<li><code>deny(C)</code> signals an error after encountering a violation of <code>C</code>,</li>
<li><code>allow(C)</code> overrides the check for <code>C</code> so that violations will go
unreported,</li>
<li><code>forbid(C)</code> is the same as <code>deny(C)</code>, but also forbids changing the lint
level afterwards.</li>
</ul>

<p>The lint checks supported by the compiler can be found via <code>rustc -W help</code>,
along with their default settings.</p>
<pre class="rust "><span class="kw">mod</span> <span class="ident">m1</span> {<span class="comment">
    // Missing documentation is ignored here
    </span><span class="attribute">#[<span class="ident">allow</span>(<span class="ident">missing_doc</span>)]</span>
    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">undocumented_one</span>() <span class="op">-&gt;</span> <span class="ident">int</span> { <span class="number">1</span> }<span class="comment">

    // Missing documentation signals a warning here
    </span><span class="attribute">#[<span class="ident">warn</span>(<span class="ident">missing_doc</span>)]</span>
    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">undocumented_too</span>() <span class="op">-&gt;</span> <span class="ident">int</span> { <span class="number">2</span> }<span class="comment">

    // Missing documentation signals an error here
    </span><span class="attribute">#[<span class="ident">deny</span>(<span class="ident">missing_doc</span>)]</span>
    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">undocumented_end</span>() <span class="op">-&gt;</span> <span class="ident">int</span> { <span class="number">3</span> }
}
</pre>

<p>This example shows how one can use <code>allow</code> and <code>warn</code> to toggle
a particular check on and off.</p>
<pre class="rust "><span class="attribute">#[<span class="ident">warn</span>(<span class="ident">missing_doc</span>)]</span>
<span class="kw">mod</span> <span class="ident">m2</span>{
    <span class="attribute">#[<span class="ident">allow</span>(<span class="ident">missing_doc</span>)]</span>
    <span class="kw">mod</span> <span class="ident">nested</span> {<span class="comment">
        // Missing documentation is ignored here
        </span><span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">undocumented_one</span>() <span class="op">-&gt;</span> <span class="ident">int</span> { <span class="number">1</span> }<span class="comment">

        // Missing documentation signals a warning here,
        // despite the allow above.
        </span><span class="attribute">#[<span class="ident">warn</span>(<span class="ident">missing_doc</span>)]</span>
        <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">undocumented_two</span>() <span class="op">-&gt;</span> <span class="ident">int</span> { <span class="number">2</span> }
    }<span class="comment">

    // Missing documentation signals a warning here
    </span><span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">undocumented_too</span>() <span class="op">-&gt;</span> <span class="ident">int</span> { <span class="number">3</span> }
}
</pre>

<p>This example shows how one can use <code>forbid</code> to disallow uses
of <code>allow</code> for that lint check.</p>
<pre class="rust "><span class="attribute">#[<span class="ident">forbid</span>(<span class="ident">missing_doc</span>)]</span>
<span class="kw">mod</span> <span class="ident">m3</span> {<span class="comment">
    // Attempting to toggle warning signals an error here
    </span><span class="attribute">#[<span class="ident">allow</span>(<span class="ident">missing_doc</span>)]</span>
    <span class="doccomment">/// Returns 2.
</span>    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">undocumented_too</span>() <span class="op">-&gt;</span> <span class="ident">int</span> { <span class="number">2</span> }
}
</pre>

<h3 id="language-items" class="section-header"><a href="#language-items">6.3.9 Language items(语言项目)</a></h3>
<p>Some primitive Rust operations are defined in Rust code, rather than being
implemented directly in C or assembly language.  The definitions of these
operations have to be easy for the compiler to find.  The <code>lang</code> attribute
makes it possible to declare these operations.  For example, the <code>str</code> module
in the Rust standard library defines the string equality function:</p>
<pre class="rust "><span class="attribute">#[<span class="ident">lang</span><span class="op">=</span><span class="string">"str_eq"</span>]</span>
<span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">eq_slice</span>(<span class="ident">a</span>: <span class="kw-2">&amp;</span><span class="ident">str</span>, <span class="ident">b</span>: <span class="kw-2">&amp;</span><span class="ident">str</span>) <span class="op">-&gt;</span> <span class="ident">bool</span> {<span class="comment">
    // details elided
</span>}
</pre>

<p>The name <code>str_eq</code> has a special meaning to the Rust compiler,
and the presence of this definition means that it will use this definition
when generating calls to the string equality function.</p>

<p>A complete list of the built-in language items follows:</p>

<h4 id="built-in-traits" class="section-header"><a href="#built-in-traits">6.3.9.1 Built-in Traits(内建特性或接口)</a></h4>
<ul>
<li><code>send</code>
: Able to be sent across task boundaries.</li>
<li><code>sized</code>
: Has a size known at compile time.</li>
<li><code>copy</code>
: Types that do not move ownership when used by-value.</li>
<li><code>share</code>
: Able to be safely shared between tasks when aliased.</li>
<li><code>drop</code>
: Have destructors.</li>
</ul>

<h4 id="operators" class="section-header"><a href="#operators">6.3.9.2 Operators(运算符)</a></h4>
<p>These language items are traits:</p>

<ul>
<li><code>add</code>
: Elements can be added (for example, integers and floats).</li>
<li><code>sub</code>
: Elements can be subtracted.</li>
<li><code>mul</code>
: Elements can be multiplied.</li>
<li><code>div</code>
: Elements have a division operation.</li>
<li><code>rem</code>
: Elements have a remainder operation.</li>
<li><code>neg</code>
: Elements can be negated arithmetically.</li>
<li><code>not</code>
: Elements can be negated logically.</li>
<li><code>bitxor</code>
: Elements have an exclusive-or operation.</li>
<li><code>bitand</code>
: Elements have a bitwise <code>and</code> operation.</li>
<li><code>bitor</code>
: Elements have a bitwise <code>or</code> operation.</li>
<li><code>shl</code>
: Elements have a left shift operation.</li>
<li><code>shr</code>
: Elements have a right shift operation.</li>
<li><code>index</code>
: Elements can be indexed.</li>
<li><code>eq</code>
: Elements can be compared for equality.</li>
<li><code>ord</code>
: Elements have a partial ordering.</li>
<li><code>deref</code>
: <code>*</code> can be applied, yielding a reference to another type</li>
<li><code>deref_mut</code>
: <code>*</code> can be applied, yielding a mutable reference to another type</li>
</ul>

<p>These are functions:</p>

<ul>
<li><code>str_eq</code>
: Compare two strings (<code>&amp;str</code>) for equality.</li>
<li><code>uniq_str_eq</code>
: Compare two owned strings (<code>~str</code>) for equality.</li>
<li><code>strdup_uniq</code>
: Return a new unique string
containing a copy of the contents of a unique string.</li>
</ul>

<h4 id="types" class="section-header"><a href="#types">6.3.9.3 Types(类型)</a></h4>
<ul>
<li><code>unsafe</code>
: A type whose contents can be mutated through an immutable reference</li>
<li><code>type_id</code>
: The type returned by the <code>type_id</code> intrinsic.</li>
</ul>

<h4 id="marker-types" class="section-header"><a href="#marker-types">6.3.9.4 Marker types(标记类型)</a></h4>
<p>These types help drive the compiler's analysis</p>

<ul>
<li><code>covariant_type</code>
: The type parameter should be considered covariant</li>
<li><code>contravariant_type</code>
: The type parameter should be considered contravariant</li>
<li><code>invariant_type</code>
: The type parameter should be considered invariant</li>
<li><code>covariant_lifetime</code>
: The lifetime parameter should be considered covariant</li>
<li><code>contravariant_lifetime</code>
: The lifetime parameter should be considered contravariant</li>
<li><code>invariant_lifetime</code>
: The lifetime parameter should be considered invariant</li>
<li><code>no_send_bound</code>
: This type does not implement "send", even if eligible</li>
<li><code>no_copy_bound</code>
: This type does not implement "copy", even if eligible</li>
<li><code>no_share_bound</code>
: This type does not implement "share", even if eligible</li>
<li><p><code>managed_bound</code>
: This type implements "managed"</p></li>
<li><p><code>fail_</code>
: Abort the program with an error.</p></li>
<li><p><code>fail_bounds_check</code>
: Abort the program with a bounds check error.</p></li>
<li><p><code>exchange_malloc</code>
: Allocate memory on the exchange heap.</p></li>
<li><p><code>exchange_free</code>
: Free memory that was allocated on the exchange heap.</p></li>
<li><p><code>malloc</code>
: Allocate memory on the managed heap.</p></li>
<li><p><code>free</code>
: Free memory that was allocated on the managed heap.</p></li>
</ul>

<blockquote>
<p><strong>Note:</strong> This list is likely to become out of date. We should auto-generate it
from <code>librustc/middle/lang_items.rs</code>.</p>
</blockquote>

<h3 id="inline-attributes" class="section-header"><a href="#inline-attributes">6.3.10 Inline attributes(内联属性)</a></h3>
<p>The inline attribute is used to suggest to the compiler to perform an inline
expansion and place a copy of the function in the caller rather than generating
code to call the function where it is defined.</p>

<p>The compiler automatically inlines functions based on internal heuristics.
Incorrectly inlining functions can actually making the program slower, so it
should be used with care.</p>

<p><code>#[inline]</code> and <code>#[inline(always)]</code> always causes the function to be serialized
into crate metadata to allow cross-crate inlining.</p>

<p>There are three different types of inline attributes:</p>

<ul>
<li><code>#[inline]</code> hints the compiler to perform an inline expansion.</li>
<li><code>#[inline(always)]</code> asks the compiler to always perform an inline expansion.</li>
<li><code>#[inline(never)]</code> asks the compiler to never perform an inline expansion.</li>
</ul>

<h3 id="deriving" class="section-header"><a href="#deriving">6.3.11 Deriving(发散)</a></h3>
<p>The <code>deriving</code> attribute allows certain traits to be automatically
implemented for data structures. For example, the following will
create an <code>impl</code> for the <code>Eq</code> and <code>Clone</code> traits for <code>Foo</code>, the type
parameter <code>T</code> will be given the <code>Eq</code> or <code>Clone</code> constraints for the
appropriate <code>impl</code>:</p>
<pre class="rust "><span class="attribute">#[<span class="ident">deriving</span>(<span class="ident">Eq</span>, <span class="ident">Clone</span>)]</span>
<span class="kw">struct</span> <span class="ident">Foo</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> {
    <span class="ident">a</span>: <span class="ident">int</span>,
    <span class="ident">b</span>: <span class="ident">T</span>
}
</pre>

<p>The generated <code>impl</code> for <code>Eq</code> is equivalent to</p>
<pre class="rust "><span class="kw">impl</span><span class="op">&lt;</span><span class="ident">T</span>: <span class="ident">Eq</span><span class="op">&gt;</span> <span class="ident">Eq</span> <span class="kw">for</span> <span class="ident">Foo</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> {
    <span class="kw">fn</span> <span class="ident">eq</span>(<span class="kw-2">&amp;</span><span class="self">self</span>, <span class="ident">other</span>: <span class="kw-2">&amp;</span><span class="ident">Foo</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span>) <span class="op">-&gt;</span> <span class="ident">bool</span> {
        <span class="self">self</span>.<span class="ident">a</span> <span class="op">==</span> <span class="ident">other</span>.<span class="ident">a</span> <span class="op">&amp;&amp;</span> <span class="self">self</span>.<span class="ident">b</span> <span class="op">==</span> <span class="ident">other</span>.<span class="ident">b</span>
    }

    <span class="kw">fn</span> <span class="ident">ne</span>(<span class="kw-2">&amp;</span><span class="self">self</span>, <span class="ident">other</span>: <span class="kw-2">&amp;</span><span class="ident">Foo</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span>) <span class="op">-&gt;</span> <span class="ident">bool</span> {
        <span class="self">self</span>.<span class="ident">a</span> <span class="op">!=</span> <span class="ident">other</span>.<span class="ident">a</span> <span class="op">||</span> <span class="self">self</span>.<span class="ident">b</span> <span class="op">!=</span> <span class="ident">other</span>.<span class="ident">b</span>
    }
}
</pre>

<p>Supported traits for <code>deriving</code> are:</p>

<ul>
<li>Comparison traits: <code>Eq</code>, <code>TotalEq</code>, <code>Ord</code>, <code>TotalOrd</code>.</li>
<li>Serialization: <code>Encodable</code>, <code>Decodable</code>. These require <code>serialize</code>.</li>
<li><code>Clone</code>, to create <code>T</code> from <code>&amp;T</code> via a copy.</li>
<li><code>Hash</code>, to iterate over the bytes in a data type.</li>
<li><code>Rand</code>, to create a random instance of a data type.</li>
<li><code>Default</code>, to create an empty instance of a data type.</li>
<li><code>Zero</code>, to create a zero instance of a numeric data type.</li>
<li><code>FromPrimitive</code>, to create an instance from a numeric primitive.</li>
<li><code>Show</code>, to format a value using the <code>{}</code> formatter.</li>
</ul>

<h3 id="stability" class="section-header"><a href="#stability">6.3.12 Stability(稳定性)</a></h3>
<p>One can indicate the stability of an API using the following attributes:</p>

<ul>
<li><code>deprecated</code>: This item should no longer be used, e.g. it has been
replaced. No guarantee of backwards-compatibility.</li>
<li><code>experimental</code>: This item was only recently introduced or is
otherwise in a state of flux. It may change significantly, or even
be removed. No guarantee of backwards-compatibility.</li>
<li><code>unstable</code>: This item is still under development, but requires more
testing to be considered stable. No guarantee of backwards-compatibility.</li>
<li><code>stable</code>: This item is considered stable, and will not change
significantly. Guarantee of backwards-compatibility.</li>
<li><code>frozen</code>: This item is very stable, and is unlikely to
change. Guarantee of backwards-compatibility.</li>
<li><code>locked</code>: This item will never change unless a serious bug is
found. Guarantee of backwards-compatibility.</li>
</ul>

<p>These levels are directly inspired by
<a href="http://nodejs.org/api/documentation.html">Node.js' "stability index"</a>.</p>

<p>There are lints for disallowing items marked with certain levels:
<code>deprecated</code>, <code>experimental</code> and <code>unstable</code>; the first two will warn
by default. Items with not marked with a stability are considered to
be unstable for the purposes of the lint. One can give an optional
string that will be displayed when the lint flags the use of an item.</p>
<pre class="rust "><span class="attribute">#<span class="op">!</span>[<span class="ident">warn</span>(<span class="ident">unstable</span>)]</span>

<span class="attribute">#[<span class="ident">deprecated</span><span class="op">=</span><span class="string">"replaced by `best`"</span>]</span>
<span class="kw">fn</span> <span class="ident">bad</span>() {<span class="comment">
    // delete everything
</span>}

<span class="kw">fn</span> <span class="ident">better</span>() {<span class="comment">
    // delete fewer things
</span>}

<span class="attribute">#[<span class="ident">stable</span>]</span>
<span class="kw">fn</span> <span class="ident">best</span>() {<span class="comment">
    // delete nothing
</span>}

<span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="ident">bad</span>();<span class="comment"> // "warning: use of deprecated item: replaced by `best`"

    </span><span class="ident">better</span>();<span class="comment"> // "warning: use of unmarked item"

    </span><span class="ident">best</span>();<span class="comment"> // no warning
</span>}
</pre>

<blockquote>
<p><strong>Note:</strong> Currently these are only checked when applied to
individual functions, structs, methods and enum variants, <em>not</em> to
entire modules, traits, impls or enums themselves.</p>
</blockquote>

<h3 id="compiler-features" class="section-header"><a href="#compiler-features">6.3.13 Compiler Features(编译器功能)</a></h3>
<p>Certain aspects of Rust may be implemented in the compiler, but they're not
necessarily ready for every-day use. These features are often of "prototype
quality" or "almost production ready", but may not be stable enough to be
considered a full-fledged language feature.</p>

<p>For this reason, Rust recognizes a special crate-level attribute of the form:</p>
<pre class="rust "><span class="attribute">#<span class="op">!</span>[<span class="ident">feature</span>(<span class="ident">feature1</span>, <span class="ident">feature2</span>, <span class="ident">feature3</span>)]</span>
</pre>

<p>This directive informs the compiler that the feature list: <code>feature1</code>,
<code>feature2</code>, and <code>feature3</code> should all be enabled. This is only recognized at a
crate-level, not at a module-level. Without this directive, all features are
considered off, and using the features will result in a compiler error.</p>

<p>The currently implemented features of the reference compiler are:</p>

<ul>
<li><p><code>macro_rules</code> - The definition of new macros. This does not encompass
              macro-invocation, that is always enabled by default, this only
              covers the definition of new macros. There are currently
              various problems with invoking macros, how they interact with
              their environment, and possibly how they are used outside of
              location in which they are defined. Macro definitions are
              likely to change slightly in the future, so they are currently
              hidden behind this feature.</p></li>
<li><p><code>globs</code> - Importing everything in a module through <code>*</code>. This is currently a
        large source of bugs in name resolution for Rust, and it's not clear
        whether this will continue as a feature or not. For these reasons,
        the glob import statement has been hidden behind this feature flag.</p></li>
<li><p><code>struct_variant</code> - Structural enum variants (those with named fields). It is
                 currently unknown whether this style of enum variant is as
                 fully supported as the tuple-forms, and it's not certain
                 that this style of variant should remain in the language.
                 For now this style of variant is hidden behind a feature
                 flag.</p></li>
<li><p><code>once_fns</code> - Onceness guarantees a closure is only executed once. Defining a
           closure as <code>once</code> is unlikely to be supported going forward. So
           they are hidden behind this feature until they are to be removed.</p></li>
<li><p><code>managed_boxes</code> - Usage of <code>@</code> pointers is gated due to many
                planned changes to this feature. In the past, this has meant
                "a GC pointer", but the current implementation uses
                reference counting and will likely change drastically over
                time. Additionally, the <code>@</code> syntax will no longer be used to
                create GC boxes.</p></li>
<li><p><code>asm</code> - The <code>asm!</code> macro provides a means for inline assembly. This is often
      useful, but the exact syntax for this feature along with its semantics
      are likely to change, so this macro usage must be opted into.</p></li>
<li><p><code>non_ascii_idents</code> - The compiler supports the use of non-ascii identifiers,
                   but the implementation is a little rough around the
                   edges, so this can be seen as an experimental feature for
                   now until the specification of identifiers is fully
                   fleshed out.</p></li>
<li><p><code>thread_local</code> - The usage of the <code>#[thread_local]</code> attribute is experimental
               and should be seen as unstable. This attribute is used to
               declare a <code>static</code> as being unique per-thread leveraging
               LLVM's implementation which works in concert with the kernel
               loader and dynamic linker. This is not necessarily available
               on all platforms, and usage of it is discouraged (rust
               focuses more on task-local data instead of thread-local
               data).</p></li>
<li><p><code>link_args</code> - This attribute is used to specify custom flags to the linker,
            but usage is strongly discouraged. The compiler's usage of the
            system linker is not guaranteed to continue in the future, and
            if the system linker is not used then specifying custom flags
            doesn't have much meaning.</p></li>
</ul>

<p>If a feature is promoted to a language feature, then all existing programs will
start to receive compilation warnings about #[feature] directives which enabled
the new feature (because the directive is no longer necessary). However, if
a feature is decided to be removed from the language, errors will be issued (if
there isn't a parser error first). The directive in this case is no longer
necessary, and it's likely that existing code will break if the feature isn't
removed.</p>

<p>If a unknown feature is found in a directive, it results in a compiler error. An
unknown feature is one which has never been recognized by the compiler.</p>

<h1 id="statements-and-expressions" class="section-header"><a href="#statements-and-expressions">7 Statements and expressions(语句和表达式)</a></h1>
<p>Rust is <em>primarily</em> an expression language. This means that most forms of
value-producing or effect-causing evaluation are directed by the uniform
syntax category of <em>expressions</em>. Each kind of expression can typically <em>nest</em>
within each other kind of expression, and rules for evaluation of expressions
involve specifying both the value produced by the expression and the order in
which its sub-expressions are themselves evaluated.</p>

<p>In contrast, statements in Rust serve <em>mostly</em> to contain and explicitly
sequence expression evaluation.</p>
Rust基本是一个表达式语言.这话的意思是绝大多数形式的值生成或者操作效果评估都是同一形式的某种表达式.<br/>
每个种类的表达式典型的都可以嵌入到其他种类的表达式以及表达式评估规则里涉及表达式生成的值和
它们自己评估的子表达式的顺序.<br>相比之下.Rust的语句绝大多数包含明确的表达式评估顺序.
<h2 id="statements" class="section-header"><a href="#statements">7.1 Statements(语句)</a></h2>
<p>A <em>statement</em> is a component of a block, which is in turn a component of an
outer <a href="#expressions">expression</a> or <a href="#functions">function</a>.</p>
语句是一个块的组成部分.而这个块又是外部的表达式或者函数的一个组成部分.
<p>Rust has two kinds of statement:
<a href="#declaration-statements">declaration statements</a> and
<a href="#expression-statements">expression statements</a>.</p>
Rust有两个种类的语句:声明语句和表达式语句.
<h3 id="declaration-statements" class="section-header"><a href="#declaration-statements">7.1.1 Declaration statements(声明语句)</a></h3>
<p>A <em>declaration statement</em> is one that introduces one or more <em>names</em> into the enclosing statement block.
The declared names may denote new slots or new items.</p>
声明语句是引入一个名字或多个名字到一个封闭语句块内.声明的名字表示一个新的插槽或者新的项目.
<h4 id="item-declarations" class="section-header"><a href="#item-declarations">7.1.1.1 Item declarations(项目声明)</a></h4>
<p>An <em>item declaration statement</em> has a syntactic form identical to an
<a href="#items">item</a> declaration within a module. Declaring an item — a function,
enumeration, structure, type, static, trait, implementation or module — locally
within a statement block is simply a way of restricting its scope to a narrow
region containing all of its uses; it is otherwise identical in meaning to
declaring the item outside the statement block.</p>
项目声明语句和模块的项目声明具有相同的语法形式.声明一个项目-函数,枚举,结构,类型,静态,特性,实现或者模块
--模块是本地一个语句块比较简单的方法用来限制它的范围在一个狭窄的区域内包含所有它用到的东西;
另外在语句块外使用声明项目也有同样的意义.
<p>Note: there is no implicit capture of the function's dynamic environment when
declaring a function-local item.</p>
说明:当声明一个函数局部项目的时候,没有隐含的扑捉函数的动态环境.
<h4 id="slot-declarations" class="section-header"><a href="#slot-declarations">7.1.1.2 Slot declarations(插槽声明)</a></h4>
<pre><code class="language-{.notrust">let_decl : "let" pat [':' type ] ? [ init ] ? ';' ;
init : [ '=' ] expr ;</code></pre>

<p>A <em>slot declaration</em> introduces a new set of slots, given by a pattern.
The pattern may be followed by a type annotation, and/or an initializer expression.
When no type annotation is given, the compiler will infer the type,
or signal an error if insufficient type information is available for definite inference.
Any slots introduced by a slot declaration are visible from the point of declaration until the end of the enclosing block scope.</p>
插槽(slot)声明通过模式引入一组新的插槽.模式可以是:类型注解,或者初始化表达式.<br/>
当没有给出类型注释,编译器将推断类型,或者在类型信息不足够明确的推断类型的时候给出错误信息.
<h3 id="expression-statements" class="section-header"><a href="#expression-statements">7.1.2 Expression statements(表达式语句)</a></h3>
<p>An <em>expression statement</em> is one that evaluates an <a href="#expressions">expression</a>
and ignores its result.
The type of an expression statement <code>e;</code> is always <code>()</code>, regardless of the type of <code>e</code>.
As a rule, an expression statement's purpose is to trigger the effects of evaluating its expression.</p>
表达式语句是评估表达式并忽略它的结果.类型表达式语句 <code>e;</code> 总是返回<code>()</code>,而不管<code>e</code>的类型
一般来说,表达式语句的目的是为了触发评估它的表达式的效果.
<h2 id="expressions" class="section-header"><a href="#expressions">7.2 Expressions(表达式)</a></h2>
<p>An expression may have two roles: it always produces a <em>value</em>, and it may have <em>effects</em>
(otherwise known as "side effects").
An expression <em>evaluates to</em> a value, and has effects during <em>evaluation</em>.
Many expressions contain sub-expressions (operands).
The meaning of each kind of expression dictates several things:
  * Whether or not to evaluate the sub-expressions when evaluating the expression
  * The order in which to evaluate the sub-expressions
  * How to combine the sub-expressions' values to obtain the value of the expression.</p>
一个表达式一般有两个角色:它总是产生一个值;它总有效果(也被称为"副作用").
一个表达式评估产生一个值并且评估时有效果.许多表达式包含子表达式(操作数).<br>
这就是说每个类型的表达式决定了几个事情:<br>
* 在评估表达式的时候是否也评估子表达式<br>
*评估子表达式的顺序<br>
*如何结合子表达式的值来获得表达式的值<br>
<p>In this way, the structure of expressions dictates the structure of execution.
Blocks are just another kind of expression,
so blocks, statements, expressions, and blocks again can recursively nest inside each other
to an arbitrary depth.</p>
通过这个方式,表达式的结构决定了执行的结构.<br>
块只是另外种类的表达式<br>
因此块,语句,表达式和块重复可以递归彼此相互嵌入到任意深度.
<h4 id="lvalues,-rvalues-and-temporaries" class="section-header"><a href="#lvalues,-rvalues-and-temporaries">7.2.0.1 Lvalues, rvalues and temporaries(左值,右值和临时值)</a></h4>
<p>Expressions are divided into two main categories: <em>lvalues</em> and <em>rvalues</em>.
Likewise within each expression, sub-expressions may occur in <em>lvalue context</em> or <em>rvalue context</em>.
The evaluation of an expression depends both on its own category and the context it occurs within.</p>
表达式可以分成2个主要的类:<em>左值</em> 和 <em>右值</em>.<br>
同样在每个表达式,子表达式可以出现在<em>左值 上下文</em> 或者<em>右值 上下文</em>.
<p>An lvalue is an expression that represents a memory location. These
expressions are <a href="#path-expressions">paths</a> (which refer to local
variables, function and method arguments, or static variables),
dereferences (<code>*expr</code>), <a href="#index-expressions">indexing expressions</a>
(<code>expr[expr]</code>), and <a href="#field-expressions">field references</a> (<code>expr.f</code>).
All other expressions are rvalues.</p>
左值是表示内存位置的表达式.这些表达式是路径(引用到局部变量,函数和方法参数或者静态变量)<br>
解引用 (<code>*expr</code>)和<a href="#field-expressions">字段表达式</a> (<code>expr.f</code>).<br>
除此其他所有都属于右值.
<p>The left operand of an <a href="#assignment-expressions">assignment</a> or
<a href="#compound-assignment-expressions">compound-assignment</a> expression is an lvalue context,
as is the single operand of a unary <a href="#unary-operator-expressions">borrow</a>.
All other expression contexts are rvalue contexts.</p>
赋值或复合赋值表达式的左操作数是左值上下文,一元操作符borrow是单一操作数.<br>
所有其他的表达式上下文都是右值上下文.
<p>When an lvalue is evaluated in an <em>lvalue context</em>, it denotes a memory location;
when evaluated in an <em>rvalue context</em>, it denotes the value held <em>in</em> that memory location.</p>
当一个左值在左值上下文中被评估的时候,它表示一个内存位置;当一个右值上下文被评估的时候,它表示在内存位置中
被保管的值.
<p>When an rvalue is used in lvalue context, a temporary un-named lvalue is created and used instead.
A temporary's lifetime equals the largest lifetime of any reference that points to it.</p>
当一个右值被用在左值上下文时,一个临时的未命名的左值被建立并用来代替这个右值.<br>
临时左值的生命周期等于它的所有引用最大的生命周期.
<h4 id="moved-and-copied-types" class="section-header"><a href="#moved-and-copied-types">7.2.0.2 Moved and copied types(移动和复制类型)</a></h4>
<p>When a <a href="#memory-slots">local variable</a> is used
as an <a href="#lvalues-rvalues-and-temporaries">rvalue</a>
the variable will either be moved or copied, depending on its type.
For types that contain <a href="#pointer-types">owning pointers</a>
or values that implement the special trait <code>Drop</code>,
the variable is moved.
All other types are copied.</p>
当一个局部变量被用于右值的时候,该变量或者被移动或者被复制,要看它的类型<br>
如果类型包含<a href="#pointer-types">自有指针</a>或者值已经实现了特殊的特性(trait)<code>Drop</code>,<br>
那个这个值被移动操作.所有其他的类型都执行复制操作.
<h3 id="literal-expressions" class="section-header"><a href="#literal-expressions">7.2.1 Literal expressions(文字表达式)</a></h3>
<p>A <em>literal expression</em> consists of one of the <a href="#literals">literal</a>
forms described earlier. It directly describes a number, character,
string, boolean value, or the unit value.</p>
一个文字表达式是一个前面描述<a href="#literals">文字</a>形式..它直接描述一个数字,字符,字符串,布尔值,或者unit值<br>
<pre class="rust ">();<span class="comment">        // unit type
</span><span class="string">"hello"</span>;<span class="comment">   // string type
</span><span class="string">'5'</span>;<span class="comment">       // character type
</span><span class="number">5</span>;<span class="comment">         // integer type
</span></pre>

<h3 id="path-expressions" class="section-header"><a href="#path-expressions">7.2.2 Path expressions(路径表达式)</a></h3>
<p>A <a href="#paths">path</a> used as an expression context denotes either a local variable or an item.
Path expressions are <a href="#lvalues-rvalues-and-temporaries">lvalues</a>.</p>
路径用于表达式上下文标识一个局部变量或者一个项目.路径表达式是<a href="#lvalues-rvalues-and-temporaries">左值</a>.</p> 。
<h3 id="tuple-expressions" class="section-header"><a href="#tuple-expressions">7.2.3 Tuple expressions(元组表达式)</a></h3>
<p>Tuples are written by enclosing one or more comma-separated
expressions in parentheses. They are used to create <a href="#tuple-types">tuple-typed</a>
values.</p>
元组是写作封闭的括号内一个或多个逗号分开的表达式.它们用于建立<a href="#tuple-types">元组类型</a>
<pre class="rust ">(<span class="number">0</span>,);
(<span class="number">0.0</span>, <span class="number">4.5</span>);
(<span class="string">"a"</span>, <span class="number">4u</span>, <span class="boolval">true</span>);
</pre>

<h3 id="structure-expressions" class="section-header"><a href="#structure-expressions">7.2.4 Structure expressions(结构表达式)</a></h3>
<pre><code class="language-{.notrust">struct_expr : expr_path '{' ident ':' expr
                      [ ',' ident ':' expr ] *
                      [ ".." expr ] '}' |
              expr_path '(' expr
                      [ ',' expr ] * ')' |
              expr_path ;</code></pre>

<p>There are several forms of structure expressions.
A <em>structure expression</em> consists of the <a href="#paths">path</a> of a <a href="#structures">structure item</a>,
followed by a brace-enclosed list of one or more comma-separated name-value pairs,
providing the field values of a new instance of the structure.
A field name can be any identifier, and is separated from its value expression by a colon.
The location denoted by a structure field is mutable if and only if the enclosing structure is mutable.</p>
有数种形式的结构表达式<br>
一个结构表达式由<a href="#structures">结构项目</a>的<a href="#paths">路径</a>组成,新结构实例的字段值由封闭大括号
后面是一个或多个逗号隔开的名字-值对提供.字段名字可以是任何标识并且和它的值表达式由冒号分隔;<br>
如果一个封闭的结构是可变的,那么结构字段表示的位置也是可变的.

<p>A <em>tuple structure expression</em> consists of the <a href="#paths">path</a> of a <a href="#structures">structure item</a>,
followed by a parenthesized list of one or more comma-separated expressions
(in other words, the path of a structure item followed by a tuple expression).
The structure item must be a tuple structure item.</p>
元组结构表达式由结构项目路径组成,跟随着括号内一个或多个逗号分隔的表达式.(换句话说,结构项目路径后面是元组表达式).<br>
结构项目必须是一个元组结构项目.
<p>A <em>unit-like structure expression</em> consists only of the <a href="#paths">path</a> of a <a href="#structures">structure item</a>.</p>
unit类似结构表达式由 <a href="#structures">结构项目</a>的<a href="#paths">路径</a>组成
<p>The following are examples of structure expressions:</p>
一下是一些结构表达式例子.
<pre class="rust "><span class="ident">Point</span> {<span class="ident">x</span>: <span class="number">10.0</span>, <span class="ident">y</span>: <span class="number">20.0</span>};
<span class="ident">TuplePoint</span>(<span class="number">10.0</span>, <span class="number">20.0</span>);
<span class="kw">let</span> <span class="ident">u</span> <span class="op">=</span> <span class="ident">game</span>::<span class="ident">User</span> {<span class="ident">name</span>: <span class="string">"Joe"</span>, <span class="ident">age</span>: <span class="number">35</span>, <span class="ident">score</span>: <span class="number">100_000</span>};
<span class="ident">some_fn</span>::<span class="op">&lt;</span><span class="ident">Cookie</span><span class="op">&gt;</span>(<span class="ident">Cookie</span>);
</pre>

<p>A structure expression forms a new value of the named structure type.
Note that for a given <em>unit-like</em> structure type, this will always be the same value.</p>
结构表达式生成一个根据已命名的结构类型的新值.
<p>A structure expression can terminate with the syntax <code>..</code> followed by an expression to denote a functional update.
The expression following <code>..</code> (the base) must have the same structure type as the new structure type being formed.
The entire expression denotes the result of allocating a new structure
(with the same type as the base expression)
with the given values for the fields that were explicitly specified
and the values in the base record for all other fields.</p>
结构表达式可以用语法..来表示结束.后随的表达式表示功能更新.表达式包含<code>..</code>(the base)
必须同产生的新结构类型具有相同的结构类型.全部表达式表示新结构的结果<br>
<pre class="rust "><span class="kw">let</span> <span class="ident">base</span> <span class="op">=</span> <span class="ident">Point3d</span> {<span class="ident">x</span>: <span class="number">1</span>, <span class="ident">y</span>: <span class="number">2</span>, <span class="ident">z</span>: <span class="number">3</span>};
<span class="ident">Point3d</span> {<span class="ident">y</span>: <span class="number">0</span>, <span class="ident">z</span>: <span class="number">10</span>, .. <span class="ident">base</span>};
</pre>

<h3 id="block-expressions" class="section-header"><a href="#block-expressions">7.2.5 Block expressions(块表达式)</a></h3>
<pre><code class="language-{.notrust">block_expr : '{' [ view_item ] *
                 [ stmt ';' | item ] *
                 [ expr ] '}' ;</code></pre>

<p>A <em>block expression</em> is similar to a module in terms of the declarations that
are possible. Each block conceptually introduces a new namespace scope. View
items can bring new names into scopes and declared items are in scope for only
the block itself.</p>
块表达式和模块声明相似.每一个块概念上引进一个新的命名空间范围.可见性项目和带来新的名字并且声明性项目<br>
只在块自身内部
<p>A block will execute each statement sequentially, and then execute the
expression (if given). If the final expression is omitted, the type and return
value of the block are <code>()</code>, but if it is provided, the type and return value
of the block are that of the expression itself.</p>
块顺序执行每个语句,并执行表达式(如果有的话).如果最后表达式忽略了,那么块的返回类型和是(),但是如果提供了表达式<br>
块的返回类型和块就是表达式自身.
<h3 id="method-call-expressions" class="section-header"><a href="#method-call-expressions">7.2.6 Method-call expressions(方法调用表达式)</a></h3>
<pre><code class="language-{.notrust">method_call_expr : expr '.' ident paren_expr_list ;</code></pre>

<p>A <em>method call</em> consists of an expression followed by a single dot, an identifier, and a parenthesized expression-list.
Method calls are resolved to methods on specific traits,
either statically dispatching to a method if the exact <code>self</code>-type of the left-hand-side is known,
or dynamically dispatching if the left-hand-side expression is an indirect <a href="#object-types">object type</a>.</p>

<h3 id="field-expressions" class="section-header"><a href="#field-expressions">7.2.7 Field expressions(字段表达式)</a></h3>
<pre><code class="language-{.notrust">field_expr : expr '.' ident ;</code></pre>

<p>A <em>field expression</em> consists of an expression followed by a single dot and an identifier,
when not immediately followed by a parenthesized expression-list (the latter is a <a href="#method-call-expressions">method call expression</a>).
A field expression denotes a field of a <a href="#structure-types">structure</a>.</p>
<pre class="rust "><span class="ident">myrecord</span>.<span class="ident">myfield</span>;
<span class="ident">foo</span>().<span class="ident">x</span>;
(<span class="ident">Struct</span> {<span class="ident">a</span>: <span class="number">10</span>, <span class="ident">b</span>: <span class="number">20</span>}).<span class="ident">a</span>;
</pre>

<p>A field access on a record is an <a href="#lvalues-rvalues-and-temporaries">lvalue</a> referring to the value of that field.
When the field is mutable, it can be <a href="#assignment-expressions">assigned</a> to.</p>

<p>When the type of the expression to the left of the dot is a pointer to a record or structure,
it is automatically dereferenced to make the field access possible.</p>

<h3 id="vector-expressions" class="section-header"><a href="#vector-expressions">7.2.8 Vector expressions(向量表达式)</a></h3>
<pre><code class="language-{.notrust">vec_expr : '[' "mut" ? vec_elems? ']' ;

vec_elems : [expr [',' expr]*] | [expr ',' ".." expr] ;</code></pre>

<p>A <a href="#vector-types"><em>vector</em></a> <em>expression</em> is written by enclosing zero or
more comma-separated expressions of uniform type in square brackets.</p>
向量表达式是封闭的方括号内的0个或多个逗号分开的统一类型的表达式.
主义:矢量内必须是同一类型.
<p>In the <code>[expr ',' ".." expr]</code> form, the expression after the <code>".."</code>
must be a constant expression that can be evaluated at compile time, such
as a <a href="#literals">literal</a> or a <a href="#static-items">static item</a>.</p>
	 [expr ',' ".." expr]形式,表达式..之后必须是一个可以在编译时评估的常数表达式,<br>
	 比如<a href="#literals">文字</a>或者<a href="#static-items">静态项目</a>
<pre class="rust ">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>];
[<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>, <span class="string">"d"</span>];
[<span class="number">0</span>, ..<span class="number">128</span>];<span class="comment">             // vector with 128 zeros
</span>[<span class="number">0u8</span>, <span class="number">0u8</span>, <span class="number">0u8</span>, <span class="number">0u8</span>];
</pre>

<h3 id="index-expressions" class="section-header"><a href="#index-expressions">7.2.9 Index expressions(索引表达式)</a></h3>
<pre><code class="language-{.notrust">idx_expr : expr '[' expr ']' ;</code></pre>

<p><a href="#vector-types">Vector</a>-typed expressions can be indexed by writing a
square-bracket-enclosed expression (the index) after them. When the
vector is mutable, the resulting <a href="#lvalues-rvalues-and-temporaries">lvalue</a> can be assigned to.</p>

<p>Indices are zero-based, and may be of any integral type. Vector access
is bounds-checked at run-time. When the check fails, it will put the
task in a <em>failing state</em>.</p>
<pre class="rust ">
([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>])[<span class="number">0</span>];
([<span class="string">"a"</span>, <span class="string">"b"</span>])[<span class="number">10</span>];<span class="comment"> // fails
</span></pre>

<h3 id="unary-operator-expressions" class="section-header"><a href="#unary-operator-expressions">7.2.10 Unary operator expressions(一元运算符表达式)</a></h3>
<p>Rust defines six symbolic unary operators.
They are all written as prefix operators,
before the expression they apply to.</p>
Rust有6个基本的一元运算符,它们作为表达式的前缀运算符.
<ul>
<li><code>-</code>
: Negation. May only be applied to numeric types.</li>
负数,只能用于数字类型.
<li><p><code>*</code>
: Dereference. When applied to a <a href="#pointer-types">pointer</a> it denotes the pointed-to location.
For pointers to mutable locations, the resulting <a href="#lvalues-rvalues-and-temporaries">lvalue</a> can be assigned to.
On non-pointer types, it calls the <code>deref</code> method of the <code>std::ops::Deref</code> trait, or the
<code>deref_mut</code> method of the <code>std::ops::DerefMut</code> trait (if implemented by the type and required
for an outer expression that will or could mutate the dereference), and produces the
result of dereferencing the <code>&amp;</code> or <code>&amp;mut</code> borrowed pointer returned from the overload method.</p></li>
	解引用.当用于指针声明的时候,它表示一个地址.对一个可变的指针地址,左值的结果可以赋值给一个非指针的类型,这叫做<br>
<code>deref</code>是 <code>std::ops::Deref</code>特性的方法,			
或者<code>deref_mut</code>是<code>std::ops::DerefMut</code>特性的方法(如果类型实现并且要求一个外部表达式或许<br>改变解引用),解引用从重载的方法产果&或者&mut借指针并生成一个结果.

<li>

<p>
	<code>!</code>
: Logical negation. On the boolean type, this flips between <code>true</code> and
<code>false</code>. On integer types, this inverts the individual bits in the
two's complement representation of the value.</p></li>
逻辑否定.布尔类型在true和false之间变化.对整数类型来说，这将在各个位的二进制补码之间反转.
<li><p><code>~</code>
:  <a href="#pointer-types">Boxing</a> operators. Allocate a box to hold the value they are applied to,
 and store the value in it. <code>~</code> creates an owned box.</p></li>
 	封装运算符.申请一个封装用来保存和储存值.建立一个自由的封装.
<li><p><code>&amp;</code>
: Borrow operator. Returns a reference, pointing to its operand.
The operand of a borrow is statically proven to outlive the resulting pointer.
If the borrow-checker cannot prove this, it is a compilation error.</p></li>
借运算符.返回一个引用指向它的操作数.借来的操作数必须静态证明比指针长寿.
<br>如果borrow-checker不能证明这点，将产生一个编译错误.
</ul>

<h3 id="binary-operator-expressions" class="section-header"><a href="#binary-operator-expressions">7.2.11 Binary operator expressions(二元运算符表达式)</a></h3>
<pre><code class="language-{.notrust">binop_expr : expr binop expr ;</code></pre>

<p>Binary operators expressions are given in terms of
<a href="#operator-precedence">operator precedence</a>.</p>

<h4 id="arithmetic-operators" class="section-header"><a href="#arithmetic-operators">7.2.11.1 Arithmetic operators(算数运算符)</a></h4>
<p>Binary arithmetic expressions are syntactic sugar for calls to built-in traits,
defined in the <code>std::ops</code> module of the <code>std</code> library.
This means that arithmetic operators can be overridden for user-defined types.
The default meaning of the operators on standard types is given here.</p>

<ul>
<li><code>+</code>
: Addition and vector/string concatenation.
Calls the <code>add</code> method on the <code>std::ops::Add</code> trait.</li>
<li><code>-</code>
: Subtraction.
Calls the <code>sub</code> method on the <code>std::ops::Sub</code> trait.</li>
<li><code>*</code>
: Multiplication.
Calls the <code>mul</code> method on the <code>std::ops::Mul</code> trait.</li>
<li><code>/</code>
: Quotient.
Calls the <code>div</code> method on the <code>std::ops::Div</code> trait.</li>
<li><code>%</code>
: Remainder.
Calls the <code>rem</code> method on the <code>std::ops::Rem</code> trait.</li>
</ul>

<h4 id="bitwise-operators" class="section-header"><a href="#bitwise-operators">7.2.11.2 Bitwise operators(位运算符)</a></h4>
<p>Like the <a href="#arithmetic-operators">arithmetic operators</a>, bitwise operators
are syntactic sugar for calls to methods of built-in traits.
This means that bitwise operators can be overridden for user-defined types.
The default meaning of the operators on standard types is given here.</p>

<ul>
<li><code>&amp;</code>
: And.
Calls the <code>bitand</code> method of the <code>std::ops::BitAnd</code> trait.</li>
<li><code>|</code>
: Inclusive or.
Calls the <code>bitor</code> method of the <code>std::ops::BitOr</code> trait.</li>
<li><code>^</code>
: Exclusive or.
Calls the <code>bitxor</code> method of the <code>std::ops::BitXor</code> trait.</li>
<li><code>&lt;&lt;</code>
: Logical left shift.
Calls the <code>shl</code> method of the <code>std::ops::Shl</code> trait.</li>
<li><code>&gt;&gt;</code>
: Logical right shift.
Calls the <code>shr</code> method of the <code>std::ops::Shr</code> trait.</li>
</ul>

<h4 id="lazy-boolean-operators" class="section-header"><a href="#lazy-boolean-operators">7.2.11.3 Lazy boolean operators(惰性布尔运算符)</a></h4>
<p>The operators <code>||</code> and <code>&amp;&amp;</code> may be applied to operands of boolean type.
The <code>||</code> operator denotes logical 'or', and the <code>&amp;&amp;</code> operator denotes logical 'and'.
They differ from <code>|</code> and <code>&amp;</code> in that the right-hand operand is only evaluated
when the left-hand operand does not already determine the result of the expression.
That is, <code>||</code> only evaluates its right-hand operand
when the left-hand operand evaluates to <code>false</code>, and <code>&amp;&amp;</code> only when it evaluates to <code>true</code>.</p>

<h4 id="comparison-operators" class="section-header"><a href="#comparison-operators">7.2.11.4 Comparison operators(比较运算符)</a></h4>
<p>Comparison operators are, like the <a href="#arithmetic-operators">arithmetic operators</a>,
and <a href="#bitwise-operators">bitwise operators</a>,
syntactic sugar for calls to built-in traits.
This means that comparison operators can be overridden for user-defined types.
The default meaning of the operators on standard types is given here.</p>

<ul>
<li><code>==</code>
: Equal to.
Calls the <code>eq</code> method on the <code>std::cmp::Eq</code> trait.</li>
<li><code>!=</code>
: Unequal to.
Calls the <code>ne</code> method on the <code>std::cmp::Eq</code> trait.</li>
<li><code>&lt;</code>
: Less than.
Calls the <code>lt</code> method on the <code>std::cmp::Ord</code> trait.</li>
<li><code>&gt;</code>
: Greater than.
Calls the <code>gt</code> method on the <code>std::cmp::Ord</code> trait.</li>
<li><code>&lt;=</code>
: Less than or equal.
Calls the <code>le</code> method on the <code>std::cmp::Ord</code> trait.</li>
<li><code>&gt;=</code>
: Greater than or equal.
Calls the <code>ge</code> method on the <code>std::cmp::Ord</code> trait.</li>
</ul>

<h4 id="type-cast-expressions" class="section-header"><a href="#type-cast-expressions">7.2.11.5 Type cast expressions(类型转换表达式)</a></h4>
<p>A type cast expression is denoted with the binary operator <code>as</code>.</p>
类型转换表达式用二元运算符as来表示.
<p>Executing an <code>as</code> expression casts the value on the left-hand side to the type
on the right-hand side.</p>

<p>A numeric value can be cast to any numeric type.
A raw pointer value can be cast to or from any integral type or raw pointer type.
Any other cast is unsupported and will fail to compile.</p>
一个数字值可以转换为任意数字类型.一个原始指针值可以转换为或者转换自任何整数类型或者原始指针类型.
<a href="http://msdn.microsoft.com/en-us/library/exx3b86w%28v=vs.80%29.aspx"> integral type 参考:整数类型</a>

<p>An example of an <code>as</code> expression:</p>
<pre class="rust ">
<span class="kw">fn</span> <span class="ident">avg</span>(<span class="ident">v</span>: <span class="kw-2">&amp;</span>[<span class="ident">f64</span>]) <span class="op">-&gt;</span> <span class="ident">f64</span> {
  <span class="kw">let</span> <span class="ident">sum</span>: <span class="ident">f64</span> <span class="op">=</span> <span class="ident">sum</span>(<span class="ident">v</span>);
  <span class="kw">let</span> <span class="ident">sz</span>: <span class="ident">f64</span> <span class="op">=</span> <span class="ident">len</span>(<span class="ident">v</span>) <span class="kw">as</span> <span class="ident">f64</span>;
  <span class="kw">return</span> <span class="ident">sum</span> <span class="op">/</span> <span class="ident">sz</span>;
}
</pre>

<h4 id="assignment-expressions" class="section-header"><a href="#assignment-expressions">7.2.11.6 Assignment expressions(赋值表达式)</a></h4>
<p>An <em>assignment expression</em> consists of an <a href="#lvalues-rvalues-and-temporaries">lvalue</a> expression followed by an
equals sign (<code>=</code>) and an <a href="#lvalues-rvalues-and-temporaries">rvalue</a> expression.</p>

<p>Evaluating an assignment expression <a href="#moved-and-copied-types">either copies or moves</a> its right-hand operand to its left-hand operand.</p>
<pre class="rust ">
<span class="ident">x</span> <span class="op">=</span> <span class="ident">y</span>;
</pre>

<h4 id="compound-assignment-expressions" class="section-header"><a href="#compound-assignment-expressions">7.2.11.7 Compound assignment expressions(符合赋值表达式)</a></h4>
<p>The <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code>, <code>&amp;</code>, <code>|</code>, <code>^</code>, <code>&lt;&lt;</code>, and <code>&gt;&gt;</code>
operators may be composed with the <code>=</code> operator. The expression <code>lval
OP= val</code> is equivalent to <code>lval = lval OP val</code>. For example, <code>x = x +
1</code> may be written as <code>x += 1</code>.</p>

<p>Any such expression always has the <a href="#primitive-types"><code>unit</code></a> type.</p>

<h4 id="operator-precedence" class="section-header"><a href="#operator-precedence">7.2.11.8 Operator precedence(运算符优先权)</a></h4>
<p>The precedence of Rust binary operators is ordered as follows, going
from strong to weak:</p>

<pre><code class="language-{.notrust">* / %
as
+ -
&lt;&lt; &gt;&gt;
&amp;
^
|
&lt; &gt; &lt;= &gt;=
== !=
&amp;&amp;
||
=</code></pre>

<p>Operators at the same precedence level are evaluated left-to-right. <a href="#unary-operator-expressions">Unary operators</a>
have the same precedence level and it is stronger than any of the binary operators'.</p>

<h3 id="grouped-expressions" class="section-header"><a href="#grouped-expressions">7.2.12 Grouped expressions(分组表达式)</a></h3>
<p>An expression enclosed in parentheses evaluates to the result of the enclosed
expression.  Parentheses can be used to explicitly specify evaluation order
within an expression.</p>

<pre><code class="language-{.notrust">paren_expr : '(' expr ')' ;</code></pre>

<p>An example of a parenthesized expression:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">x</span> <span class="op">=</span> (<span class="number">2</span> <span class="op">+</span> <span class="number">3</span>) <span class="op">*</span> <span class="number">4</span>;
</pre>

<h3 id="call-expressions" class="section-header"><a href="#call-expressions">7.2.13 Call expressions(调用表达式)</a></h3>
<pre><code class="language-{.notrust">expr_list : [ expr [ ',' expr ]* ] ? ;
paren_expr_list : '(' expr_list ')' ;
call_expr : expr paren_expr_list ;</code></pre>

<p>A <em>call expression</em> invokes a function, providing zero or more input slots and
an optional reference slot to serve as the function's output, bound to the
<code>lval</code> on the right hand side of the call. If the function eventually returns,
then the expression completes.</p>

<p>Some examples of call expressions:</p>
<pre class="rust ">
<span class="kw">let</span> <span class="ident">x</span>: <span class="ident">int</span> <span class="op">=</span> <span class="ident">add</span>(<span class="number">1</span>, <span class="number">2</span>);
<span class="kw">let</span> <span class="ident">pi</span>: <span class="prelude-ty">Option</span><span class="op">&lt;</span><span class="ident">f32</span><span class="op">&gt;</span> <span class="op">=</span> <span class="ident">FromStr</span>::<span class="ident">from_str</span>(<span class="string">"3.14"</span>);
</pre>

<h3 id="lambda-expressions" class="section-header"><a href="#lambda-expressions">7.2.14 Lambda expressions(Lambda表达式)</a></h3>
<pre><code class="language-{.notrust">ident_list : [ ident [ ',' ident ]* ] ? ;
lambda_expr : '|' ident_list '|' expr ;</code></pre>

<p>A <em>lambda expression</em> (sometimes called an "anonymous function expression") defines a function and denotes it as a value,
in a single expression.
A lambda expression is a pipe-symbol-delimited (<code>|</code>) list of identifiers followed by an expression.</p>

<p>A lambda expression denotes a function that maps a list of parameters (<code>ident_list</code>)
onto the expression that follows the <code>ident_list</code>.
The identifiers in the <code>ident_list</code> are the parameters to the function.
These parameters' types need not be specified, as the compiler infers them from context.</p>

<p>Lambda expressions are most useful when passing functions as arguments to other functions,
as an abbreviation for defining and capturing a separate function.</p>

<p>Significantly, lambda expressions <em>capture their environment</em>,
which regular <a href="#functions">function definitions</a> do not.
The exact type of capture depends on the <a href="#function-types">function type</a> inferred for the lambda expression.
In the simplest and least-expensive form (analogous to a <code>|| { }</code> expression),
the lambda expression captures its environment by reference,
effectively borrowing pointers to all outer variables mentioned inside the function.
Alternately, the compiler may infer that a lambda expression should copy or move values (depending on their type.)
from the environment into the lambda expression's captured environment.</p>

<p>In this example, we define a function <code>ten_times</code> that takes a higher-order function argument,
and call it with a lambda expression as an argument.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">ten_times</span>(<span class="ident">f</span>: <span class="op">|</span><span class="ident">int</span><span class="op">|</span>) {
    <span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">i</span> <span class="op">=</span> <span class="number">0</span>;
    <span class="kw">while</span> <span class="ident">i</span> <span class="op">&lt;</span> <span class="number">10</span> {
        <span class="ident">f</span>(<span class="ident">i</span>);
        <span class="ident">i</span> <span class="op">+=</span> <span class="number">1</span>;
    }
}

<span class="ident">ten_times</span>(<span class="op">|</span><span class="ident">j</span><span class="op">|</span> <span class="macro">println</span><span class="macro">!</span>(<span class="string">"hello, {}"</span>, <span class="ident">j</span>));
</pre>

<h3 id="while-loops" class="section-header"><a href="#while-loops">7.2.15 While loops(While Loops循环)</a></h3>
<pre><code class="language-{.notrust">while_expr : "while" expr '{' block '}' ;</code></pre>

<p>A <code>while</code> loop begins by evaluating the boolean loop conditional expression.
If the loop conditional expression evaluates to <code>true</code>, the loop body block
executes and control returns to the loop conditional expression. If the loop
conditional expression evaluates to <code>false</code>, the <code>while</code> expression completes.</p>

<p>An example:</p>
<pre class="rust "><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">i</span> <span class="op">=</span> <span class="number">0</span>;

<span class="kw">while</span> <span class="ident">i</span> <span class="op">&lt;</span> <span class="number">10</span> {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"hello"</span>);
    <span class="ident">i</span> <span class="op">=</span> <span class="ident">i</span> <span class="op">+</span> <span class="number">1</span>;
}
</pre>

<h3 id="infinite-loops" class="section-header"><a href="#infinite-loops">7.2.16 Infinite loops(无限循环)</a></h3>
<p>The keyword <code>loop</code> in Rust appears both in <em>loop expressions</em> and in <em>continue expressions</em>.
A loop expression denotes an infinite loop;
see <a href="#continue-expressions">Continue expressions</a> for continue expressions.</p>

<pre><code class="language-{.notrust">loop_expr : [ lifetime ':' ] "loop" '{' block '}';</code></pre>

<p>A <code>loop</code> expression may optionally have a <em>label</em>.
If a label is present,
then labeled <code>break</code> and <code>loop</code> expressions nested within this loop may exit out of this loop or return control to its head.
See <a href="#break-expressions">Break expressions</a>.</p>

<h3 id="break-expressions" class="section-header"><a href="#break-expressions">7.2.17 Break expressions(中断表达式)</a></h3>
<pre><code class="language-{.notrust">break_expr : "break" [ lifetime ];</code></pre>

<p>A <code>break</code> expression has an optional <code>label</code>.
If the label is absent, then executing a <code>break</code> expression immediately terminates the innermost loop enclosing it.
It is only permitted in the body of a loop.
If the label is present, then <code>break foo</code> terminates the loop with label <code>foo</code>,
which need not be the innermost label enclosing the <code>break</code> expression,
but must enclose it.</p>
break表达式有一个可选label.如果没有label,执行break表达式将立即中断内部最接近的loop封闭.
如果有了label,break foo 将中断lable是foo的loop
<h3 id="continue-expressions" class="section-header"><a href="#continue-expressions">7.2.18 Continue expressions(连续表达式)</a></h3>
<pre><code class="language-{.notrust">continue_expr : "loop" [ lifetime ];</code></pre>

<p>A continue expression, written <code>loop</code>, also has an optional <code>label</code>.
If the label is absent,
then executing a <code>loop</code> expression immediately terminates the current iteration of the innermost loop enclosing it,
returning control to the loop <em>head</em>.
In the case of a <code>while</code> loop,
the head is the conditional expression controlling the loop.
In the case of a <code>for</code> loop, the head is the call-expression controlling the loop.
If the label is present, then <code>loop foo</code> returns control to the head of the loop with label <code>foo</code>,
which need not be the innermost label enclosing the <code>break</code> expression,
but must enclose it.</p>

<p>A <code>loop</code> expression is only permitted in the body of a loop.</p>

<h3 id="for-expressions" class="section-header"><a href="#for-expressions">7.2.19 For expressions(For表达式)</a></h3>
<pre><code class="language-{.notrust">for_expr : "for" pat "in" expr '{' block '}' ;</code></pre>

<p>A <code>for</code> expression is a syntactic construct for looping over elements
provided by an implementation of <code>std::iter::Iterator</code>.</p>

<p>An example of a for loop over the contents of a vector:</p>
<pre class="rust ">
<span class="kw">let</span> <span class="ident">v</span>: <span class="kw-2">&amp;</span>[<span class="ident">Foo</span>] <span class="op">=</span> <span class="kw-2">&amp;</span>[<span class="ident">a</span>, <span class="ident">b</span>, <span class="ident">c</span>];

<span class="kw">for</span> <span class="ident">e</span> <span class="kw">in</span> <span class="ident">v</span>.<span class="ident">iter</span>() {
    <span class="ident">bar</span>(<span class="op">*</span><span class="ident">e</span>);
}
</pre>

<p>An example of a for loop over a series of integers:</p>
<pre class="rust "><span class="kw">for</span> <span class="ident">i</span> <span class="kw">in</span> <span class="ident">range</span>(<span class="number">0u</span>, <span class="number">256</span>) {
    <span class="ident">bar</span>(<span class="ident">i</span>);
}
</pre>

<h3 id="if-expressions" class="section-header"><a href="#if-expressions">7.2.20 If expressions</a></h3>
<pre><code class="language-{.notrust">if_expr : "if" expr '{' block '}'
          else_tail ? ;

else_tail : "else" [ if_expr
                   | '{' block '}' ] ;</code></pre>

<p>An <code>if</code> expression is a conditional branch in program control. The form of
an <code>if</code> expression is a condition expression, followed by a consequent
block, any number of <code>else if</code> conditions and blocks, and an optional
trailing <code>else</code> block. The condition expressions must have type
<code>bool</code>. If a condition expression evaluates to <code>true</code>, the
consequent block is executed and any subsequent <code>else if</code> or <code>else</code>
block is skipped. If a condition expression evaluates to <code>false</code>, the
consequent block is skipped and any subsequent <code>else if</code> condition is
evaluated. If all <code>if</code> and <code>else if</code> conditions evaluate to <code>false</code>
then any <code>else</code> block is executed.</p>

<h3 id="match-expressions" class="section-header"><a href="#match-expressions">7.2.21 Match expressions</a></h3>
<pre><code class="language-{.notrust">match_expr : "match" expr '{' match_arm [ '|' match_arm ] * '}' ;

match_arm : match_pat "=&gt;" [ expr "," | '{' block '}' ] ;

match_pat : pat [ ".." pat ] ? [ "if" expr ] ;</code></pre>

<p>A <code>match</code> expression branches on a <em>pattern</em>. The exact form of matching that
occurs depends on the pattern. Patterns consist of some combination of
literals, destructured vectors or enum constructors, structures, records and
tuples, variable binding specifications, wildcards (<code>..</code>), and placeholders
(<code>_</code>). A <code>match</code> expression has a <em>head expression</em>, which is the value to
compare to the patterns. The type of the patterns must equal the type of the
head expression.</p>

<p>In a pattern whose head expression has an <code>enum</code> type, a placeholder (<code>_</code>)
stands for a <em>single</em> data field, whereas a wildcard <code>..</code> stands for <em>all</em> the
fields of a particular variant. For example:</p>
<pre class="rust "><span class="kw">enum</span> <span class="ident">List</span><span class="op">&lt;</span><span class="ident">X</span><span class="op">&gt;</span> { <span class="ident">Nil</span>, <span class="ident">Cons</span>(<span class="ident">X</span>, <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">List</span><span class="op">&lt;</span><span class="ident">X</span><span class="op">&gt;&gt;</span>) }

<span class="kw">let</span> <span class="ident">x</span>: <span class="ident">List</span><span class="op">&lt;</span><span class="ident">int</span><span class="op">&gt;</span> <span class="op">=</span> <span class="ident">Cons</span>(<span class="number">10</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="number">11</span>, <span class="kw">box</span> <span class="ident">Nil</span>));

<span class="kw">match</span> <span class="ident">x</span> {
    <span class="ident">Cons</span>(_, <span class="kw">box</span> <span class="ident">Nil</span>) <span class="op">=&gt;</span> <span class="macro">fail</span><span class="macro">!</span>(<span class="string">"singleton list"</span>),
    <span class="ident">Cons</span>(..)         <span class="op">=&gt;</span> <span class="kw">return</span>,
    <span class="ident">Nil</span>              <span class="op">=&gt;</span> <span class="macro">fail</span><span class="macro">!</span>(<span class="string">"empty list"</span>)
}
</pre>

<p>The first pattern matches lists constructed by applying <code>Cons</code> to any head
value, and a tail value of <code>box Nil</code>. The second pattern matches <em>any</em> list
constructed with <code>Cons</code>, ignoring the values of its arguments. The difference
between <code>_</code> and <code>..</code> is that the pattern <code>C(_)</code> is only type-correct if <code>C</code> has
exactly one argument, while the pattern <code>C(..)</code> is type-correct for any enum
variant <code>C</code>, regardless of how many arguments <code>C</code> has.</p>

<p>Used inside a vector pattern, <code>..</code> stands for any number of elements. This
wildcard can be used at most once for a given vector, which implies that it
cannot be used to specifically match elements that are at an unknown distance
from both ends of a vector, like <code>[.., 42, ..]</code>. If followed by a variable name,
it will bind the corresponding slice to the variable. Example:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">is_symmetric</span>(<span class="ident">list</span>: <span class="kw-2">&amp;</span>[<span class="ident">uint</span>]) <span class="op">-&gt;</span> <span class="ident">bool</span> {
    <span class="kw">match</span> <span class="ident">list</span> {
        [] <span class="op">|</span> [_]                   <span class="op">=&gt;</span> <span class="boolval">true</span>,
        [<span class="ident">x</span>, ..<span class="ident">inside</span>, <span class="ident">y</span>] <span class="kw">if</span> <span class="ident">x</span> <span class="op">==</span> <span class="ident">y</span> <span class="op">=&gt;</span> <span class="ident">is_symmetric</span>(<span class="ident">inside</span>),
        _                          <span class="op">=&gt;</span> <span class="boolval">false</span>
    }
}

<span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="kw">let</span> <span class="ident">sym</span>     <span class="op">=</span> <span class="kw-2">&amp;</span>[<span class="number">0</span>, <span class="number">1</span>, <span class="number">4</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">1</span>, <span class="number">0</span>];
    <span class="kw">let</span> <span class="ident">not_sym</span> <span class="op">=</span> <span class="kw-2">&amp;</span>[<span class="number">0</span>, <span class="number">1</span>, <span class="number">7</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">1</span>, <span class="number">0</span>];
    <span class="macro">assert</span><span class="macro">!</span>(<span class="ident">is_symmetric</span>(<span class="ident">sym</span>));
    <span class="macro">assert</span><span class="macro">!</span>(<span class="op">!</span><span class="ident">is_symmetric</span>(<span class="ident">not_sym</span>));
}
</pre>

<p>A <code>match</code> behaves differently depending on whether or not the head expression
is an <a href="#lvalues-rvalues-and-temporaries">lvalue or an rvalue</a>.
If the head expression is an rvalue, it is
first evaluated into a temporary location, and the resulting value
is sequentially compared to the patterns in the arms until a match
is found. The first arm with a matching pattern is chosen as the branch target
of the <code>match</code>, any variables bound by the pattern are assigned to local
variables in the arm's block, and control enters the block.</p>

<p>When the head expression is an lvalue, the match does not allocate a
temporary location (however, a by-value binding may copy or move from
the lvalue). When possible, it is preferable to match on lvalues, as the
lifetime of these matches inherits the lifetime of the lvalue, rather
than being restricted to the inside of the match.</p>

<p>An example of a <code>match</code> expression:</p>
<pre class="rust ">
<span class="kw">enum</span> <span class="ident">List</span><span class="op">&lt;</span><span class="ident">X</span><span class="op">&gt;</span> { <span class="ident">Nil</span>, <span class="ident">Cons</span>(<span class="ident">X</span>, <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">List</span><span class="op">&lt;</span><span class="ident">X</span><span class="op">&gt;&gt;</span>) }

<span class="kw">let</span> <span class="ident">x</span>: <span class="ident">List</span><span class="op">&lt;</span><span class="ident">int</span><span class="op">&gt;</span> <span class="op">=</span> <span class="ident">Cons</span>(<span class="number">10</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="number">11</span>, <span class="kw">box</span> <span class="ident">Nil</span>));

<span class="kw">match</span> <span class="ident">x</span> {
    <span class="ident">Cons</span>(<span class="ident">a</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="ident">b</span>, _)) <span class="op">=&gt;</span> {
        <span class="ident">process_pair</span>(<span class="ident">a</span>,<span class="ident">b</span>);
    }
    <span class="ident">Cons</span>(<span class="number">10</span>, _) <span class="op">=&gt;</span> {
        <span class="ident">process_ten</span>();
    }
    <span class="ident">Nil</span> <span class="op">=&gt;</span> {
        <span class="kw">return</span>;
    }
    _ <span class="op">=&gt;</span> {
        <span class="macro">fail</span><span class="macro">!</span>();
    }
}
</pre>

<p>Patterns that bind variables
default to binding to a copy or move of the matched value
(depending on the matched value's type).
This can be changed to bind to a reference by
using the <code>ref</code> keyword,
or to a mutable reference using <code>ref mut</code>.</p>

<p>Subpatterns can also be bound to variables by the use of the syntax
<code>variable @ pattern</code>.
For example:</p>
<pre class="rust "><span class="kw">enum</span> <span class="ident">List</span> { <span class="ident">Nil</span>, <span class="ident">Cons</span>(<span class="ident">uint</span>, <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">List</span><span class="op">&gt;</span>) }

<span class="kw">fn</span> <span class="ident">is_sorted</span>(<span class="ident">list</span>: <span class="kw-2">&amp;</span><span class="ident">List</span>) <span class="op">-&gt;</span> <span class="ident">bool</span> {
    <span class="kw">match</span> <span class="op">*</span><span class="ident">list</span> {
        <span class="ident">Nil</span> <span class="op">|</span> <span class="ident">Cons</span>(_, <span class="kw">box</span> <span class="ident">Nil</span>) <span class="op">=&gt;</span> <span class="boolval">true</span>,
        <span class="ident">Cons</span>(<span class="ident">x</span>, <span class="kw-2">ref</span> <span class="ident">r</span> <span class="kw-2">@</span> <span class="kw">box</span> <span class="ident">Cons</span>(<span class="ident">y</span>, _)) <span class="op">=&gt;</span> (<span class="ident">x</span> <span class="op">&lt;=</span> <span class="ident">y</span>) <span class="op">&amp;&amp;</span> <span class="ident">is_sorted</span>(<span class="op">*</span><span class="ident">r</span>)
    }
}

<span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="kw">let</span> <span class="ident">a</span> <span class="op">=</span> <span class="ident">Cons</span>(<span class="number">6</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="number">7</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="number">42</span>, <span class="kw">box</span> <span class="ident">Nil</span>)));
    <span class="macro">assert</span><span class="macro">!</span>(<span class="ident">is_sorted</span>(<span class="kw-2">&amp;</span><span class="ident">a</span>));
}
</pre>

<p>Patterns can also dereference pointers by using the <code>&amp;</code>,
<code>~</code> or <code>@</code> symbols, as appropriate. For example, these two matches
on <code>x: &amp;int</code> are equivalent:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">y</span> <span class="op">=</span> <span class="kw">match</span> <span class="op">*</span><span class="ident">x</span> { <span class="number">0</span> <span class="op">=&gt;</span> <span class="string">"zero"</span>, _ <span class="op">=&gt;</span> <span class="string">"some"</span> };
<span class="kw">let</span> <span class="ident">z</span> <span class="op">=</span> <span class="kw">match</span> <span class="ident">x</span> { <span class="kw-2">&amp;</span><span class="number">0</span> <span class="op">=&gt;</span> <span class="string">"zero"</span>, _ <span class="op">=&gt;</span> <span class="string">"some"</span> };

<span class="macro">assert_eq</span><span class="macro">!</span>(<span class="ident">y</span>, <span class="ident">z</span>);
</pre>

<p>A pattern that's just an identifier, like <code>Nil</code> in the previous example,
could either refer to an enum variant that's in scope, or bind a new variable.
The compiler resolves this ambiguity by forbidding variable bindings that occur
in <code>match</code> patterns from shadowing names of variants that are in scope.
For example, wherever <code>List</code> is in scope,
a <code>match</code> pattern would not be able to bind <code>Nil</code> as a new name.
The compiler interprets a variable pattern <code>x</code> as a binding <em>only</em> if there is
no variant named <code>x</code> in scope.
A convention you can use to avoid conflicts is simply to name variants with
upper-case letters, and local variables with lower-case letters.</p>

<p>Multiple match patterns may be joined with the <code>|</code> operator.
A range of values may be specified with <code>..</code>.
For example:</p>
<pre class="rust ">
<span class="kw">let</span> <span class="ident">message</span> <span class="op">=</span> <span class="kw">match</span> <span class="ident">x</span> {
  <span class="number">0</span> <span class="op">|</span> <span class="number">1</span>  <span class="op">=&gt;</span> <span class="string">"not many"</span>,
  <span class="number">2</span> .. <span class="number">9</span> <span class="op">=&gt;</span> <span class="string">"a few"</span>,
  _      <span class="op">=&gt;</span> <span class="string">"lots"</span>
};
</pre>

<p>Range patterns only work on scalar types
(like integers and characters; not like vectors and structs, which have sub-components).
A range pattern may not be a sub-range of another range pattern inside the same <code>match</code>.</p>

<p>Finally, match patterns can accept <em>pattern guards</em> to further refine the
criteria for matching a case. Pattern guards appear after the pattern and
consist of a bool-typed expression following the <code>if</code> keyword. A pattern
guard may refer to the variables bound within the pattern they follow.</p>
<pre class="rust ">
<span class="kw">let</span> <span class="ident">message</span> <span class="op">=</span> <span class="kw">match</span> <span class="ident">maybe_digit</span> {
  <span class="prelude-val">Some</span>(<span class="ident">x</span>) <span class="kw">if</span> <span class="ident">x</span> <span class="op">&lt;</span> <span class="number">10</span> <span class="op">=&gt;</span> <span class="ident">process_digit</span>(<span class="ident">x</span>),
  <span class="prelude-val">Some</span>(<span class="ident">x</span>) <span class="op">=&gt;</span> <span class="ident">process_other</span>(<span class="ident">x</span>),
  <span class="prelude-val">None</span> <span class="op">=&gt;</span> <span class="macro">fail</span><span class="macro">!</span>()
};
</pre>

<h3 id="return-expressions" class="section-header"><a href="#return-expressions">7.2.22 Return expressions(返回表达式)</a></h3>
<pre><code class="language-{.notrust">return_expr : "return" expr ? ;</code></pre>

<p>Return expressions are denoted with the keyword <code>return</code>. Evaluating a <code>return</code>
expression moves its argument into the output slot of the current
function, destroys the current function activation frame, and transfers
control to the caller frame.</p>

<p>An example of a <code>return</code> expression:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">max</span>(<span class="ident">a</span>: <span class="ident">int</span>, <span class="ident">b</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> <span class="ident">int</span> {
   <span class="kw">if</span> <span class="ident">a</span> <span class="op">&gt;</span> <span class="ident">b</span> {
      <span class="kw">return</span> <span class="ident">a</span>;
   }
   <span class="kw">return</span> <span class="ident">b</span>;
}
</pre>

<h1 id="type-system" class="section-header"><a href="#type-system">8 Type system(类型系统,介绍Rust数据类型章节)</a></h1>
<h2 id="types-1" class="section-header"><a href="#types-1">8.1 Types</a></h2>
<p>Every slot, item and value in a Rust program has a type. The <em>type</em> of a <em>value</em>
defines the interpretation of the memory holding it.</p>

<p>Built-in types and type-constructors are tightly integrated into the language,
in nontrivial ways that are not possible to emulate in user-defined
types. User-defined types have limited capabilities.</p>

<h3 id="primitive-types" class="section-header"><a href="#primitive-types">8.1.1 Primitive types(基本类型)</a></h3>
<p>The primitive types are the following:</p>

<ul>
<li>The "unit" type <code>()</code>, having the single "unit" value <code>()</code> (occasionally called
"nil"). <sup id="fnref3"><a href="#fn3" rel="footnote">3</a></sup></li>
<li>The boolean type <code>bool</code> with values <code>true</code> and <code>false</code>.</li>
<li>The machine types.</li>
<li>The machine-dependent integer and floating-point types.</li>
</ul>

<h4 id="machine-types" class="section-header"><a href="#machine-types">8.1.1.1 Machine types(机器类型)</a></h4>
<p>The machine types are the following:</p>

<ul>
<li><p>The unsigned word types <code>u8</code>, <code>u16</code>, <code>u32</code> and <code>u64</code>, with values drawn from
the integer intervals [0, 2<sup>8</sup> - 1], [0, 2<sup>16</sup> - 1], [0, 2<sup>32</sup> - 1] and
[0, 2<sup>64</sup> - 1] respectively.</p></li>
<li><p>The signed two's complement word types <code>i8</code>, <code>i16</code>, <code>i32</code> and <code>i64</code>, with
values drawn from the integer intervals [-(2<sup>7</sup>), 2<sup>7</sup> - 1],
[-(2<sup>15</sup>), 2<sup>15</sup> - 1], [-(2<sup>31</sup>), 2<sup>31</sup> - 1], [-(2<sup>63</sup>), 2<sup>63</sup> - 1]
respectively.</p></li>
<li><p>The IEEE 754-2008 <code>binary32</code> and <code>binary64</code> floating-point types: <code>f32</code> and
<code>f64</code>, respectively.</p></li>
</ul>

<h4 id="machine-dependent-integer-types" class="section-header"><a href="#machine-dependent-integer-types">8.1.1.2 Machine-dependent integer types(机器相关整数类型)</a></h4>
<p>The Rust type <code>uint</code> <sup id="fnref4"><a href="#fn4" rel="footnote">4</a></sup> is an
unsigned integer type with target-machine-dependent size. Its size, in
bits, is equal to the number of bits required to hold any memory address on
the target machine.</p>

<p>The Rust type <code>int</code> <sup id="fnref5"><a href="#fn5" rel="footnote">5</a></sup>  is a
two's complement signed integer type with target-machine-dependent size. Its
size, in bits, is equal to the size of the rust type <code>uint</code> on the same target
machine.</p>

<h3 id="textual-types" class="section-header"><a href="#textual-types">8.1.2 Textual types(文本类型)</a></h3>
<p>The types <code>char</code> and <code>str</code> hold textual data.</p>

<p>A value of type <code>char</code> is a <a href="http://www.unicode.org/glossary/#unicode_scalar_value">Unicode scalar value</a>
(ie. a code point that is not a surrogate),
represented as a 32-bit unsigned word in the 0x0000 to 0xD7FF
or 0xE000 to 0x10FFFF range.
A <code>[char]</code> vector is effectively an UCS-4 / UTF-32 string.</p>

<p>A value of type <code>str</code> is a Unicode string,
represented as a vector of 8-bit unsigned bytes holding a sequence of UTF-8 codepoints.
Since <code>str</code> is of unknown size, it is not a <em>first class</em> type,
but can only be instantiated through a pointer type,
such as <code>&amp;str</code> or <code>~str</code>.</p>

<h3 id="tuple-types" class="section-header"><a href="#tuple-types">8.1.3 Tuple types(元组类型)</a></h3>
<p>The tuple type-constructor forms a new heterogeneous product of values similar
to the record type-constructor. The differences are as follows:</p>
元组类型构造形成新的类似于记录类型构造值.不同之处在于:
<ul>
<li>tuple elements cannot be mutable, unlike record fields</li>
元组元素不能被修改，同record字段不同.
<li>tuple elements are not named and can be accessed only by pattern-matching</li>
元组元素不能被命名只能通过模式匹配来访问.
</ul>

<p>Tuple types and values are denoted by listing the types or values of their
elements, respectively, in a parenthesized, comma-separated
list.</p>

<p>The members of a tuple are laid out in memory contiguously, like a record, in
order specified by the tuple type.</p>

<p>An example of a tuple type and its use:</p>
<pre class="rust "><span class="kw">type</span> <span class="ident">Pair</span><span class="op">&lt;</span><span class="lifetime">'a</span><span class="op">&gt;</span> <span class="op">=</span> (<span class="ident">int</span>,<span class="kw-2">&amp;</span><span class="lifetime">'a</span> <span class="ident">str</span>);
<span class="kw">let</span> <span class="ident">p</span>: <span class="ident">Pair</span><span class="op">&lt;</span><span class="lifetime">'static</span><span class="op">&gt;</span> <span class="op">=</span> (<span class="number">10</span>,<span class="string">"hello"</span>);
<span class="kw">let</span> (<span class="ident">a</span>, <span class="ident">b</span>) <span class="op">=</span> <span class="ident">p</span>;
<span class="macro">assert</span><span class="macro">!</span>(<span class="ident">b</span> <span class="op">!=</span> <span class="string">"world"</span>);
</pre>

<h3 id="vector-types" class="section-header"><a href="#vector-types">8.1.4 Vector types(矢量类型)</a></h3>
<p>The vector type constructor represents a homogeneous array of values of a given type.
A vector has a fixed size.
(Operations like <code>vec.push</code> operate solely on owned vectors.)
A vector type can be annotated with a <em>definite</em> size, such as <code>[int, ..10]</code>.
Such a definite-sized vector type is a first-class type, since its size is known statically.
A vector without such a size is said to be of <em>indefinite</em> size,
and is therefore not a <em>first-class</em> type.
An indefinite-size vector can only be instantiated through a pointer type,
such as <code>&amp;[T]</code> or <code>~[T]</code>.
The kind of a vector type depends on the kind of its element type,
as with other simple structural types.</p>

<p>Expressions producing vectors of definite size cannot be evaluated in a
context expecting a vector of indefinite size; one must copy the
definite-sized vector contents into a distinct vector of indefinite size.</p>

<p>An example of a vector type and its use:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">v</span>: <span class="kw-2">&amp;</span>[<span class="ident">int</span>] <span class="op">=</span> <span class="kw-2">&amp;</span>[<span class="number">7</span>, <span class="number">5</span>, <span class="number">3</span>];
<span class="kw">let</span> <span class="ident">i</span>: <span class="ident">int</span> <span class="op">=</span> <span class="ident">v</span>[<span class="number">2</span>];
<span class="macro">assert</span><span class="macro">!</span>(<span class="ident">i</span> <span class="op">==</span> <span class="number">3</span>);
</pre>

<p>All in-bounds elements of a vector are always initialized,
and access to a vector is always bounds-checked.</p>

<h3 id="structure-types" class="section-header"><a href="#structure-types">8.1.5 Structure types(结构类型)</a></h3>
<p>A <code>struct</code> <em>type</em> is a heterogeneous product of other types, called the <em>fields</em>
of the type.<sup id="fnref6"><a href="#fn6" rel="footnote">6</a></sup></p>

<p>New instances of a <code>struct</code> can be constructed with a <a href="#structure-expressions">struct expression</a>.</p>

<p>The memory order of fields in a <code>struct</code> is given by the item defining it.
Fields may be given in any order in a corresponding struct <em>expression</em>;
the resulting <code>struct</code> value will always be laid out in memory in the order specified by the corresponding <em>item</em>.</p>

<p>The fields of a <code>struct</code> may be qualified by <a href="#re-exporting-and-visibility">visibility modifiers</a>,
to restrict access to implementation-private data in a structure.</p>

<p>A <em>tuple struct</em> type is just like a structure type, except that the fields are anonymous.</p>
<em>元组结构</em>类型同结构类型相似，除了字段是匿名的.
<p>A <em>unit-like struct</em> type is like a structure type, except that it has no fields.
The one value constructed by the associated <a href="#structure-expressions">structure expression</a>
is the only value that inhabits such a type.</p>
<em>unit-like 结构</em>和结构类型相似，除了它没有字段.

<h3 id="enumerated-types" class="section-header"><a href="#enumerated-types">8.1.6 Enumerated types(枚举类型)</a></h3>
<p>An <em>enumerated type</em> is a nominal, heterogeneous disjoint union type,
denoted by the name of an <a href="#enumerations"><code>enum</code> item</a>. <sup id="fnref7"><a href="#fn7" rel="footnote">7</a></sup></p>

<p>An <a href="#enumerations"><code>enum</code> item</a> declares both the type and a number of <em>variant constructors</em>,
each of which is independently named and takes an optional tuple of arguments.</p>

<p>New instances of an <code>enum</code> can be constructed by calling one of the variant constructors,
in a <a href="#call-expressions">call expression</a>.</p>

<p>Any <code>enum</code> value consumes as much memory as the largest variant constructor for its corresponding <code>enum</code> type.</p>

<p>Enum types cannot be denoted <em>structurally</em> as types,
but must be denoted by named reference to an <a href="#enumerations"><code>enum</code> item</a>.</p>

<h3 id="recursive-types" class="section-header"><a href="#recursive-types">8.1.7 Recursive types(递归类型)</a></h3>
<p>Nominal types — <a href="#enumerated-types">enumerations</a> and <a href="#structure-types">structures</a> — may be recursive.
That is, each <code>enum</code> constructor or <code>struct</code> field may refer, directly or indirectly, to the enclosing <code>enum</code> or <code>struct</code> type itself.
Such recursion has restrictions:</p>

<ul>
<li>Recursive types must include a nominal type in the recursion
(not mere <a href="#type-definitions">type definitions</a>,
or other structural types such as <a href="#vector-types">vectors</a> or <a href="#tuple-types">tuples</a>).</li>
<li>A recursive <code>enum</code> item must have at least one non-recursive constructor
(in order to give the recursion a basis case).</li>
<li>The size of a recursive type must be finite;
in other words the recursive fields of the type must be <a href="#pointer-types">pointer types</a>.</li>
<li>Recursive type definitions can cross module boundaries, but not module <em>visibility</em> boundaries,
or crate boundaries (in order to simplify the module system and type checker).</li>
</ul>

<p>An example of a <em>recursive</em> type and its use:</p>
<pre class="rust "><span class="kw">enum</span> <span class="ident">List</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> {
  <span class="ident">Nil</span>,
  <span class="ident">Cons</span>(<span class="ident">T</span>, <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">List</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;&gt;</span>)
}

<span class="kw">let</span> <span class="ident">a</span>: <span class="ident">List</span><span class="op">&lt;</span><span class="ident">int</span><span class="op">&gt;</span> <span class="op">=</span> <span class="ident">Cons</span>(<span class="number">7</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="number">13</span>, <span class="kw">box</span> <span class="ident">Nil</span>));
</pre>

<h3 id="pointer-types" class="section-header"><a href="#pointer-types">8.1.8 Pointer types(指针类型)</a></h3>
<p>All pointers in Rust are explicit first-class values.
They can be copied, stored into data structures, and returned from functions.
There are four varieties of pointer in Rust:</p>

<ul>
<li><p>Owning pointers (<code>~</code>)
: These point to owned heap allocations (or "boxes") in the shared, inter-task heap.
Each owned box has a single owning pointer; pointer and pointee retain a 1:1 relationship at all times.
Owning pointers are written <code>~content</code>,
for example <code>~int</code> means an owning pointer to an owned box containing an integer.
Copying an owned box is a "deep" operation:
it involves allocating a new owned box and copying the contents of the old box into the new box.
Releasing an owning pointer immediately releases its corresponding owned box.</p></li>
自有指针
<li><p>References (<code>&amp;</code>)
: These point to memory <em>owned by some other value</em>.
References arise by (automatic) conversion from owning pointers, managed pointers,
or by applying the borrowing operator <code>&amp;</code> to some other value,
including <a href="#lvalues-rvalues-and-temporaries">lvalues, rvalues or temporaries</a>.
References are written <code>&amp;content</code>, or in some cases <code>&amp;'f content</code> for some lifetime-variable <code>f</code>,
for example <code>&amp;int</code> means a reference to an integer.
Copying a reference is a "shallow" operation:
it involves only copying the pointer itself.
Releasing a reference typically has no effect on the value it points to,
with the exception of temporary values,
which are released when the last reference to them is released.</p></li>
引用指针
<li><p>Raw pointers (<code>*</code>)
: Raw pointers are pointers without safety or liveness guarantees.
Raw pointers are written <code>*content</code>,
for example <code>*int</code> means a raw pointer to an integer.
Copying or dropping a raw pointer has no effect on the lifecycle of any other value.
Dereferencing a raw pointer or converting it to any other pointer type is an <a href="#unsafe-functions"><code>unsafe</code> operation</a>.
Raw pointers are generally discouraged in Rust code;
they exist to support interoperability with foreign code,
and writing performance-critical or low-level functions.</p></li>
原始指针
</ul>

<h3 id="function-types" class="section-header"><a href="#function-types">8.1.9 Function types(函数类型)</a></h3>
<p>The function type constructor <code>fn</code> forms new function types.
A function type consists of a possibly-empty set of function-type modifiers
(such as <code>unsafe</code> or <code>extern</code>), a sequence of input types and an output type.</p>

<p>An example of a <code>fn</code> type:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">add</span>(<span class="ident">x</span>: <span class="ident">int</span>, <span class="ident">y</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> <span class="ident">int</span> {
  <span class="kw">return</span> <span class="ident">x</span> <span class="op">+</span> <span class="ident">y</span>;
}

<span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">x</span> <span class="op">=</span> <span class="ident">add</span>(<span class="number">5</span>,<span class="number">7</span>);

<span class="kw">type</span> <span class="ident">Binop</span><span class="op">&lt;</span><span class="lifetime">'a</span><span class="op">&gt;</span> <span class="op">=</span> <span class="op">|</span><span class="ident">int</span>,<span class="ident">int</span><span class="op">|</span>: <span class="lifetime">'a</span> <span class="op">-&gt;</span> <span class="ident">int</span>;
<span class="kw">let</span> <span class="ident">bo</span>: <span class="ident">Binop</span> <span class="op">=</span> <span class="ident">add</span>;
<span class="ident">x</span> <span class="op">=</span> <span class="ident">bo</span>(<span class="number">5</span>,<span class="number">7</span>);
</pre>

<h3 id="closure-types" class="section-header"><a href="#closure-types">8.1.10 Closure types(闭包类型)</a></h3>
<pre><code class="language-{.notrust">closure_type := [ 'unsafe' ] [ '&lt;' lifetime-list '&gt;' ] '|' arg-list '|'
                [ ':' bound-list ] [ '-&gt;' type ]
procedure_type := 'proc' [ '&lt;' lifetime-list '&gt;' ] '(' arg-list ')'
                  [ ':' bound-list ] [ '-&gt;' type ]
lifetime-list := lifetime | lifetime ',' lifetime-list
arg-list := ident ':' type | ident ':' type ',' arg-list
bound-list := bound | bound '+' bound-list
bound := path | lifetime</code></pre>

<p>The type of a closure mapping an input of type <code>A</code> to an output of type <code>B</code> is
<code>|A| -&gt; B</code>. A closure with no arguments or return values has type <code>||</code>.
Similarly, a procedure mapping <code>A</code> to <code>B</code> is <code>proc(A) -&gt; B</code> and a no-argument
and no-return value closure has type <code>proc()</code>.</p>

<p>An example of creating and calling a closure:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">captured_var</span> <span class="op">=</span> <span class="number">10</span>;

<span class="kw">let</span> <span class="ident">closure_no_args</span> <span class="op">=</span> <span class="op">||</span> <span class="macro">println</span><span class="macro">!</span>(<span class="string">"captured_var={}"</span>, <span class="ident">captured_var</span>);

<span class="kw">let</span> <span class="ident">closure_args</span> <span class="op">=</span> <span class="op">|</span><span class="ident">arg</span>: <span class="ident">int</span><span class="op">|</span> <span class="op">-&gt;</span> <span class="ident">int</span> {
  <span class="macro">println</span><span class="macro">!</span>(<span class="string">"captured_var={}, arg={}"</span>, <span class="ident">captured_var</span>, <span class="ident">arg</span>);
  <span class="ident">arg</span><span class="comment"> // Note lack of semicolon after 'arg'
</span>};

<span class="kw">fn</span> <span class="ident">call_closure</span>(<span class="ident">c1</span>: <span class="op">||</span>, <span class="ident">c2</span>: <span class="op">|</span><span class="ident">int</span><span class="op">|</span> <span class="op">-&gt;</span> <span class="ident">int</span>) {
  <span class="ident">c1</span>();
  <span class="ident">c2</span>(<span class="number">2</span>);
}

<span class="ident">call_closure</span>(<span class="ident">closure_no_args</span>, <span class="ident">closure_args</span>);
</pre>

<p>Unlike closures, procedures may only be invoked once, but own their
environment, and are allowed to move out of their environment. Procedures are
allocated on the heap (unlike closures). An example of creating and calling a
procedure:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">string</span> <span class="op">=</span> <span class="string">"Hello"</span>.<span class="ident">to_owned</span>();<span class="comment">

// Creates a new procedure, passing it to the `spawn` function.
</span><span class="ident">spawn</span>(<span class="kw">proc</span>() {
  <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{} world!"</span>, <span class="ident">string</span>);
});<span class="comment">

// the variable `string` has been moved into the previous procedure, so it is
// no longer usable.


// Create an invoke a procedure. Note that the procedure is *moved* when
// invoked, so it cannot be invoked again.
</span><span class="kw">let</span> <span class="ident">f</span> <span class="op">=</span> <span class="kw">proc</span>(<span class="ident">n</span>: <span class="ident">int</span>) { <span class="ident">n</span> <span class="op">+</span> <span class="number">22</span> };
<span class="macro">println</span><span class="macro">!</span>(<span class="string">"answer: {}"</span>, <span class="ident">f</span>(<span class="number">20</span>));
</pre>

<h3 id="object-types" class="section-header"><a href="#object-types">8.1.11 Object types(对象类型)</a></h3>
<p>Every trait item (see <a href="#traits">traits</a>) defines a type with the same name as the trait.
This type is called the <em>object type</em> of the trait.
Object types permit "late binding" of methods, dispatched using <em>virtual method tables</em> ("vtables").
Whereas most calls to trait methods are "early bound" (statically resolved) to specific implementations at compile time,
a call to a method on an object type is only resolved to a vtable entry at compile time.
The actual implementation for each vtable entry can vary on an object-by-object basis.</p>

<p>Given a pointer-typed expression <code>E</code> of type <code>&amp;T</code> or <code>~T</code>, where <code>T</code> implements trait <code>R</code>,
casting <code>E</code> to the corresponding pointer type <code>&amp;R</code> or <code>~R</code> results in a value of the <em>object type</em> <code>R</code>.
This result is represented as a pair of pointers:
the vtable pointer for the <code>T</code> implementation of <code>R</code>, and the pointer value of <code>E</code>.</p>

<p>An example of an object type:</p>
<pre class="rust "><span class="kw">trait</span> <span class="ident">Printable</span> {
  <span class="kw">fn</span> <span class="ident">to_string</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="kw-2">~</span><span class="ident">str</span>;
}

<span class="kw">impl</span> <span class="ident">Printable</span> <span class="kw">for</span> <span class="ident">int</span> {
  <span class="kw">fn</span> <span class="ident">to_string</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="kw-2">~</span><span class="ident">str</span> { <span class="self">self</span>.<span class="ident">to_str</span>() }
}

<span class="kw">fn</span> <span class="ident">print</span>(<span class="ident">a</span>: <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Printable</span><span class="op">&gt;</span>) {
   <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">a</span>.<span class="ident">to_string</span>());
}

<span class="kw">fn</span> <span class="ident">main</span>() {
   <span class="ident">print</span>(<span class="kw">box</span> <span class="number">10</span> <span class="kw">as</span> <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Printable</span><span class="op">&gt;</span>);
}
</pre>

<p>In this example, the trait <code>Printable</code> occurs as an object type in both the type signature of <code>print</code>,
and the cast expression in <code>main</code>.</p>

<h3 id="type-parameters-1" class="section-header"><a href="#type-parameters-1">8.1.12 Type parameters(类型参数)</a></h3>
<p>Within the body of an item that has type parameter declarations, the names of its type parameters are types:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">map</span><span class="op">&lt;</span><span class="ident">A</span>: <span class="ident">Clone</span>, <span class="ident">B</span>: <span class="ident">Clone</span><span class="op">&gt;</span>(<span class="ident">f</span>: <span class="op">|</span><span class="ident">A</span><span class="op">|</span> <span class="op">-&gt;</span> <span class="ident">B</span>, <span class="ident">xs</span>: <span class="kw-2">&amp;</span>[<span class="ident">A</span>]) <span class="op">-&gt;</span> <span class="ident">Vec</span><span class="op">&lt;</span><span class="ident">B</span><span class="op">&gt;</span> {
    <span class="kw">if</span> <span class="ident">xs</span>.<span class="ident">len</span>() <span class="op">==</span> <span class="number">0</span> {
       <span class="kw">return</span> <span class="macro">vec</span><span class="macro">!</span>[];
    }
    <span class="kw">let</span> <span class="ident">first</span>: <span class="ident">B</span> <span class="op">=</span> <span class="ident">f</span>(<span class="ident">xs</span>[<span class="number">0</span>].<span class="ident">clone</span>());
    <span class="kw">let</span> <span class="ident">rest</span>: <span class="ident">Vec</span><span class="op">&lt;</span><span class="ident">B</span><span class="op">&gt;</span> <span class="op">=</span> <span class="ident">map</span>(<span class="ident">f</span>, <span class="ident">xs</span>.<span class="ident">slice</span>(<span class="number">1</span>, <span class="ident">xs</span>.<span class="ident">len</span>()));
    <span class="kw">return</span> <span class="macro">vec</span><span class="macro">!</span>[<span class="ident">first</span>].<span class="ident">append</span>(<span class="ident">rest</span>.<span class="ident">as_slice</span>());
}
</pre>

<p>Here, <code>first</code> has type <code>B</code>, referring to <code>map</code>'s <code>B</code> type parameter;
and <code>rest</code> has type <code>Vec&lt;B&gt;</code>, a vector type with element type <code>B</code>.</p>

<h3 id="self-types" class="section-header"><a href="#self-types">8.1.13 Self types(Self类型，类似this指针)</a></h3>
<p>The special type <code>self</code> has a meaning within methods inside an
impl item. It refers to the type of the implicit <code>self</code> argument. For
example, in:</p>
<pre class="rust "><span class="kw">trait</span> <span class="ident">Printable</span> {
  <span class="kw">fn</span> <span class="ident">make_string</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="kw-2">~</span><span class="ident">str</span>;
}

<span class="kw">impl</span> <span class="ident">Printable</span> <span class="kw">for</span> <span class="kw-2">~</span><span class="ident">str</span> {
    <span class="kw">fn</span> <span class="ident">make_string</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="kw-2">~</span><span class="ident">str</span> {
        (<span class="op">*</span><span class="self">self</span>).<span class="ident">clone</span>()
    }
}
</pre>

<p><code>self</code> refers to the value of type <code>~str</code> that is the receiver for a
call to the method <code>make_string</code>.</p>

<h2 id="type-kinds" class="section-header"><a href="#type-kinds">8.2 Type kinds(类型种类)</a></h2>
<p>Types in Rust are categorized into kinds, based on various properties of the components of the type.
The kinds are:</p>

<ul>
<li><code>Send</code>
: Types of this kind can be safely sent between tasks.
This kind includes scalars, owning pointers, owned closures, and
structural types containing only other owned types.
All <code>Send</code> types are <code>'static</code>.</li>
<li><code>Copy</code>
: Types of this kind consist of "Plain Old Data"
which can be copied by simply moving bits.
All values of this kind can be implicitly copied.
This kind includes scalars and immutable references,
as well as structural types containing other <code>Copy</code> types.</li>
<li><code>'static</code>
: Types of this kind do not contain any references (except for
references with the <code>static</code> lifetime, which are allowed).
This can be a useful guarantee for code
that breaks borrowing assumptions
using <a href="#unsafe-functions"><code>unsafe</code> operations</a>.</li>
<li><p><code>Drop</code>
: This is not strictly a kind,
but its presence interacts with kinds:
the <code>Drop</code> trait provides a single method <code>drop</code>
that takes no parameters,
and is run when values of the type are dropped.
Such a method is called a "destructor",
and are always executed in "top-down" order:
a value is completely destroyed
before any of the values it owns run their destructors.
Only <code>Send</code> types can implement <code>Drop</code>.</p></li>
<li><p><em>Default</em>
: Types with destructors, closure environments,
and various other <em>non-first-class</em> types,
are not copyable at all.
Such types can usually only be accessed through pointers,
or in some cases, moved between mutable locations.</p></li>
</ul>

<p>Kinds can be supplied as <em>bounds</em> on type parameters, like traits,
in which case the parameter is constrained to types satisfying that kind.</p>

<p>By default, type parameters do not carry any assumed kind-bounds at all.
When instantiating a type parameter,
the kind bounds on the parameter are checked
to be the same or narrower than the kind
of the type that it is instantiated with.</p>

<p>Sending operations are not part of the Rust language,
but are implemented in the library.
Generic functions that send values
bound the kind of these values to sendable.</p>

<h1 id="memory-and-concurrency-models" class="section-header"><a href="#memory-and-concurrency-models">9 Memory and concurrency models(内存和并发模型)</a></h1>
<p>Rust has a memory model centered around concurrently-executing <em>tasks</em>. Thus
its memory model and its concurrency model are best discussed simultaneously,
as parts of each only make sense when considered from the perspective of the
other.</p>

<p>When reading about the memory model, keep in mind that it is partitioned in
order to support tasks; and when reading about tasks, keep in mind that their
isolation and communication mechanisms are only possible due to the ownership
and lifetime semantics of the memory model.</p>

<h2 id="memory-model" class="section-header"><a href="#memory-model">9.1 Memory model(内存模型)</a></h2>
<p>A Rust program's memory consists of a static set of <em>items</em>, a set of
<a href="#tasks">tasks</a> each with its own <em>stack</em>, and a <em>heap</em>. Immutable portions of
the heap may be shared between tasks, mutable portions may not.</p>
Rust程序的模型是由一组静态的项目,一组自带堆栈的tasks和堆(heap)组成.堆heap不可变部分可以在任务tasks之间
分享,可变的部分不可以.
<p>Allocations in the stack consist of <em>slots</em>, and allocations in the heap
consist of <em>boxes</em>.</p>
堆栈分配由slots组成,堆中(heap)申请由boxes(封箱)组成.
<h3 id="memory-allocation-and-lifetime" class="section-header"><a href="#memory-allocation-and-lifetime">9.1.1 Memory allocation and lifetime(内存申请和生命周期)</a></h3>
<p>The <em>items</em> of a program are those functions, modules and types
that have their value calculated at compile-time and stored uniquely in the
memory image of the rust process. Items are neither dynamically allocated nor
freed.</p>

<p>A task's <em>stack</em> consists of activation frames automatically allocated on
entry to each function as the task executes. A stack allocation is reclaimed
when control leaves the frame containing it.</p>

<p>The <em>heap</em> is a general term that describes two separate sets of boxes:
managed boxes — which may be subject to garbage collection — and owned
boxes.  The lifetime of an allocation in the heap depends on the lifetime of
the box values pointing to it. Since box values may themselves be passed in
and out of frames, or stored in the heap, heap allocations may outlive the
frame they are allocated within.</p>
堆heap一般术语描述两组分开的封箱集合:可管理的封箱-用于垃圾回收-以及自由的封箱。
在堆的申请的声明周期依赖于封箱值的指向.当封箱值被传递出或传递进框架或者储存在堆里,
堆(heap)申请也许会比封箱申请所在的frame要长命。
<h3 id="memory-ownership" class="section-header"><a href="#memory-ownership">9.1.2 Memory ownership(内存所有权)</a></h3>
<p>A task owns all memory it can <em>safely</em> reach through local variables,
as well as managed, owned boxes and references.</p>

<p>When a task sends a value that has the <code>Send</code> trait to another task,
it loses ownership of the value sent and can no longer refer to it.
This is statically guaranteed by the combined use of "move semantics",
and the compiler-checked <em>meaning</em> of the <code>Send</code> trait:
it is only instantiated for (transitively) sendable kinds of data constructor and pointers,
never including managed boxes or references.</p>

<p>When a stack frame is exited, its local allocations are all released, and its
references to boxes (both managed and owned) are dropped.</p>

<p>A managed box may (in the case of a recursive, mutable managed type) be cyclic;
in this case the release of memory inside the managed structure may be deferred
until task-local garbage collection can reclaim it. Code can ensure no such
delayed deallocation occurs by restricting itself to owned boxes and similar
unmanaged kinds of data.</p>

<p>When a task finishes, its stack is necessarily empty and it therefore has no
references to any boxes; the remainder of its heap is immediately freed.</p>

<h3 id="memory-slots" class="section-header"><a href="#memory-slots">9.1.3 Memory slots(内存插槽)</a></h3>
<p>A task's stack contains slots.</p>

<p>A <em>slot</em> is a component of a stack frame, either a function parameter,
a <a href="#lvalues-rvalues-and-temporaries">temporary</a>, or a local variable.</p>

<p>A <em>local variable</em> (or <em>stack-local</em> allocation) holds a value directly,
allocated within the stack's memory. The value is a part of the stack frame.</p>

<p>Local variables are immutable unless declared otherwise like: <code>let mut x = ...</code>.</p>

<p>Function parameters are immutable unless declared with <code>mut</code>. The
<code>mut</code> keyword applies only to the following parameter (so <code>|mut x, y|</code>
and <code>fn f(mut x: ~int, y: ~int)</code> declare one mutable variable <code>x</code> and
one immutable variable <code>y</code>).</p>

<p>Methods that take either <code>self</code> or <code>~self</code> can optionally place them in a
mutable slot by prefixing them with <code>mut</code> (similar to regular arguments):</p>
<pre class="rust "><span class="kw">trait</span> <span class="ident">Changer</span> {
    <span class="kw">fn</span> <span class="ident">change</span>(<span class="kw-2">mut</span> <span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">Self</span>;
    <span class="kw">fn</span> <span class="ident">modify</span>(<span class="kw-2">mut</span> <span class="kw-2">~</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Self</span><span class="op">&gt;</span>;
}
</pre>

<p>Local variables are not initialized when allocated; the entire frame worth of
local variables are allocated at once, on frame-entry, in an uninitialized
state. Subsequent statements within a function may or may not initialize the
local variables. Local variables can be used only after they have been
initialized; this is enforced by the compiler.</p>

<h3 id="owned-boxes" class="section-header"><a href="#owned-boxes">9.1.4 Owned boxes(自有的封箱)</a></h3>
<p>An  <em>owned box</em> is a reference to a heap allocation holding another value, which is constructed
by the prefix operator <code>box</code>. When the standard library is in use, the type of an owned box is
<code>std::owned::Box&lt;T&gt;</code>.</p>

<p>An example of an owned box type and value:</p>
<pre class="rust ">
<span class="kw">let</span> <span class="ident">x</span>: <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">int</span><span class="op">&gt;</span> <span class="op">=</span> <span class="kw">box</span> <span class="number">10</span>;
</pre>

<p>Owned box values exist in 1:1 correspondence with their heap 
allocation
copying an owned box value makes a shallow copy of the pointer
Rust will consider a shallow copy of an owned box to move ownership of 
the value. After a value has been moved, the source location cannot be 
used unless it is reinitialized.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">x</span>: <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">int</span><span class="op">&gt;</span> <span class="op">=</span> <span class="kw">box</span> <span class="number">10</span>;
<span class="kw">let</span> <span class="ident">y</span> <span class="op">=</span> <span class="ident">x</span>;<span class="comment">
// attempting to use `x` will result in an error here
</span></pre>

<h2 id="tasks" class="section-header"><a href="#tasks">9.2 Tasks(任务)</a></h2>
<p>An executing Rust program consists of a tree of tasks.
A Rust <em>task</em> consists of an entry function, a stack,
a set of outgoing communication channels and incoming communication ports,
and ownership of some portion of the heap of a single operating-system process.
(We expect that many programs will not use channels and ports directly,
but will instead use higher-level abstractions provided in standard libraries,
such as pipes.)</p>

<p>Multiple Rust tasks may coexist in a single operating-system process.
The runtime scheduler maps tasks to a certain number of operating-system threads.
By default, the scheduler chooses the number of threads based on
the number of concurrent physical CPUs detected at startup.
It's also possible to override this choice at runtime.
When the number of tasks exceeds the number of threads — which is likely —
the scheduler multiplexes the tasks onto threads.<sup id="fnref8"><a href="#fn8" rel="footnote">8</a></sup></p>

<h3 id="communication-between-tasks" class="section-header"><a href="#communication-between-tasks">9.2.1 Communication between tasks(任务之间通讯)</a></h3>
<p>Rust tasks are isolated and generally unable to interfere with one another's memory directly,
except through <a href="#unsafe-functions"><code>unsafe</code> code</a>.
All contact between tasks is mediated by safe forms of ownership transfer,
and data races on memory are prohibited by the type system.</p>

<p>Inter-task communication and co-ordination facilities are provided in the standard library.
These include:</p>

<ul>
<li>synchronous and asynchronous communication channels with various communication topologies</li>
<li>read-only and read-write shared variables with various safe mutual exclusion patterns</li>
<li>simple locks and semaphores</li>
</ul>

<p>When such facilities carry values, the values are restricted to the <a href="#type-kinds"><code>Send</code> type-kind</a>.
Restricting communication interfaces to this kind ensures that no references or managed pointers move between tasks.
Thus access to an entire data structure can be mediated through its owning "root" value;
no further locking or copying is required to avoid data races within the substructure of such a value.</p>

<h3 id="task-lifecycle" class="section-header"><a href="#task-lifecycle">9.2.2 Task lifecycle(任务生命周期)</a></h3>
<p>The <em>lifecycle</em> of a task consists of a finite set of states and events
that cause transitions between the states. The lifecycle states of a task are:</p>

<ul>
<li>running</li>
<li>blocked</li>
<li>failing</li>
<li>dead</li>
</ul>

<p>A task begins its lifecycle — once it has been spawned — in the <em>running</em>
state. In this state it executes the statements of its entry function, and any
functions called by the entry function.</p>

<p>A task may transition from the <em>running</em> state to the <em>blocked</em>
state any time it makes a blocking communication call. When the
call can be completed — when a message arrives at a sender, or a
buffer opens to receive a message — then the blocked task will
unblock and transition back to <em>running</em>.</p>

<p>A task may transition to the <em>failing</em> state at any time, due being
killed by some external event or internally, from the evaluation of a
<code>fail!()</code> macro. Once <em>failing</em>, a task unwinds its stack and
transitions to the <em>dead</em> state. Unwinding the stack of a task is done by
the task itself, on its own control stack. If a value with a destructor is
freed during unwinding, the code for the destructor is run, also on the task's
control stack. Running the destructor code causes a temporary transition to a
<em>running</em> state, and allows the destructor code to cause any subsequent
state transitions.  The original task of unwinding and failing thereby may
suspend temporarily, and may involve (recursive) unwinding of the stack of a
failed destructor. Nonetheless, the outermost unwinding activity will continue
until the stack is unwound and the task transitions to the <em>dead</em>
state. There is no way to "recover" from task failure.  Once a task has
temporarily suspended its unwinding in the <em>failing</em> state, failure
occurring from within this destructor results in <em>hard</em> failure.
A hard failure currently results in the process aborting.</p>

<p>A task in the <em>dead</em> state cannot transition to other states; it exists
only to have its termination status inspected by other tasks, and/or to await
reclamation when the last reference to it drops.</p>

<h3 id="task-scheduling" class="section-header"><a href="#task-scheduling">9.2.3 Task scheduling(任务调度)</a></h3>
<p>The currently scheduled task is given a finite <em>time slice</em> in which to
execute, after which it is <em>descheduled</em> at a loop-edge or similar
preemption point, and another task within is scheduled, pseudo-randomly.</p>

<p>An executing task can yield control at any time, by making a library call to
<code>std::task::yield</code>, which deschedules it immediately. Entering any other
non-executing state (blocked, dead) similarly deschedules the task.</p>

<h1 id="runtime-services,-linkage-and-debugging" class="section-header"><a href="#runtime-services,-linkage-and-debugging">10 Runtime services, linkage and debugging(运行时服务,链接和调试)</a></h1>
<p>The Rust <em>runtime</em> is a relatively compact collection of C++ and Rust code
that provides fundamental services and datatypes to all Rust tasks at
run-time. It is smaller and simpler than many modern language runtimes. It is
tightly integrated into the language's execution model of memory, tasks,
communication and logging.</p>

<blockquote>
<p><strong>Note:</strong> The runtime library will merge with the <code>std</code> library in future versions of Rust.</p>
</blockquote>

<h3 id="memory-allocation" class="section-header"><a href="#memory-allocation">10.0.1 Memory allocation(内存申请)</a></h3>
<p>The runtime memory-management system is based on a <em>service-provider interface</em>,
through which the runtime requests blocks of memory from its environment
and releases them back to its environment when they are no longer needed.
The default implementation of the service-provider interface
consists of the C runtime functions <code>malloc</code> and <code>free</code>.</p>

<p>The runtime memory-management system, in turn, supplies Rust tasks with
facilities for allocating releasing stacks, as well as allocating and freeing
heap data.</p>

<h3 id="built-in-types" class="section-header"><a href="#built-in-types">10.0.2 Built in types(内建类型)</a></h3>
<p>The runtime provides C and Rust code to assist with various built-in types,
such as vectors, strings, and the low level communication system (ports,
channels, tasks).</p>

<p>Support for other built-in types such as simple types, tuples, records, and
enums is open-coded by the Rust compiler.</p>

<h3 id="task-scheduling-and-communication" class="section-header"><a href="#task-scheduling-and-communication">10.0.3 Task scheduling and communication(任务调度和通讯)</a></h3>
<p>The runtime provides code to manage inter-task communication.  This includes
the system of task-lifecycle state transitions depending on the contents of
queues, as well as code to copy values between queues and their recipients and
to serialize values for transmission over operating-system inter-process
communication facilities.</p>

<h3 id="linkage" class="section-header"><a href="#linkage">10.0.4 Linkage(链接)</a></h3>
<p>The Rust compiler supports various methods to link crates together both
statically and dynamically. This section will explore the various methods to
link Rust crates together, and more information about native libraries can be
found in the <a href="http://static.rust-lang.org/doc/master/guide-ffi.html">ffi tutorial</a>.</p>

<p>In one session of compilation, the compiler can generate multiple artifacts
through the usage of either command line flags or the <code>crate_type</code> attribute.
If one or more command line flag is specified, all <code>crate_type</code> attributes will
be ignored in favor of only building the artifacts specified by command line.</p>

<ul>
<li><p><code>--crate-type=bin</code>, <code>#[crate_type = "bin"]</code> - A runnable executable will be
produced.  This requires that there is a <code>main</code> function in the crate which
will be run when the program begins executing. This will link in all Rust and
native dependencies, producing a distributable binary.</p></li>
<li><p><code>--crate-type=lib</code>, <code>#[crate_type = "lib"]</code> - A Rust library will be produced.
This is an ambiguous concept as to what exactly is produced because a library
can manifest itself in several forms. The purpose of this generic <code>lib</code> option
is to generate the "compiler recommended" style of library. The output library
will always be usable by rustc, but the actual type of library may change from
time-to-time. The remaining output types are all different flavors of
libraries, and the <code>lib</code> type can be seen as an alias for one of them (but the
actual one is compiler-defined).</p></li>
<li><p><code>--crate-type=dylib</code>, <code>#[crate_type = "dylib"]</code> - A dynamic Rust library will
be produced. This is different from the <code>lib</code> output type in that this forces
dynamic library generation. The resulting dynamic library can be used as a
dependency for other libraries and/or executables.  This output type will
create <code>*.so</code> files on linux, <code>*.dylib</code> files on osx, and <code>*.dll</code> files on
windows.</p></li>
<li><p><code>--crate-type=staticlib</code>, <code>#[crate_type = "staticlib"]</code> - A static system
library will be produced. This is different from other library outputs in that
the Rust compiler will never attempt to link to <code>staticlib</code> outputs. The
purpose of this output type is to create a static library containing all of
the local crate's code along with all upstream dependencies. The static
library is actually a <code>*.a</code> archive on linux and osx and a <code>*.lib</code> file on
windows. This format is recommended for use in situtations such as linking
Rust code into an existing non-Rust application because it will not have
dynamic dependencies on other Rust code.</p></li>
<li><p><code>--crate-type=rlib</code>, <code>#[crate_type = "rlib"]</code> - A "Rust library" file will be
produced.  This is used as an intermediate artifact and can be thought of as a
"static Rust library". These <code>rlib</code> files, unlike <code>staticlib</code> files, are
interpreted by the Rust compiler in future linkage. This essentially means
that <code>rustc</code> will look for metadata in <code>rlib</code> files like it looks for metadata
in dynamic libraries. This form of output is used to produce statically linked
executables as well as <code>staticlib</code> outputs.</p></li>
</ul>

<p>Note that these outputs are stackable in the sense that if multiple are
specified, then the compiler will produce each form of output at once without
having to recompile. However, this only applies for outputs specified by the same
method. If only <code>crate_type</code> attributes are specified, then they will all be
built, but if one or more <code>--crate-type</code> command line flag is specified,
then only those outputs will be built.</p>

<p>With all these different kinds of outputs, if crate A depends on crate B, then
the compiler could find B in various different forms throughout the system. The
only forms looked for by the compiler, however, are the <code>rlib</code> format and the
dynamic library format. With these two options for a dependent library, the
compiler must at some point make a choice between these two formats. With this
in mind, the compiler follows these rules when determining what format of
dependencies will be used:</p>

<ol>
<li><p>If a dynamic library is being produced, then it is required for all upstream
Rust dependencies to also be dynamic. This is a limitation of the current
implementation of the linkage model.  The reason behind this limitation is to
prevent multiple copies of the same upstream library from showing up, and in
the future it is planned to support a mixture of dynamic and static linking.</p>

<p>When producing a dynamic library, the compiler will generate an error if an
upstream dependency could not be found, and also if an upstream dependency
could only be found in an <code>rlib</code> format. Remember that <code>staticlib</code> formats
are always ignored by <code>rustc</code> for crate-linking purposes.</p></li>
<li><p>If a static library is being produced, all upstream dependencies are
required to be available in <code>rlib</code> formats. This requirement stems from the
same reasons that a dynamic library must have all dynamic dependencies.</p>

<p>Note that it is impossible to link in native dynamic dependencies to a static
library, and in this case warnings will be printed about all unlinked native
dynamic dependencies.</p></li>
<li><p>If an <code>rlib</code> file is being produced, then there are no restrictions on what
format the upstream dependencies are available in. It is simply required that
all upstream dependencies be available for reading metadata from.</p>

<p>The reason for this is that <code>rlib</code> files do not contain any of their upstream
dependencies. It wouldn't be very efficient for all <code>rlib</code> files to contain a
copy of <code>libstd.rlib</code>!</p></li>
<li><p>If an executable is being produced, then things get a little interesting. As
with the above limitations in dynamic and static libraries, it is required
for all upstream dependencies to be in the same format. The next question is
whether to prefer a dynamic or a static format. The compiler currently favors
static linking over dynamic linking, but this can be inverted with the <code>-C
prefer-dynamic</code> flag to the compiler.</p>

<p>What this means is that first the compiler will attempt to find all upstream
dependencies as <code>rlib</code> files, and if successful, it will create a statically
linked executable. If an upstream dependency is missing as an <code>rlib</code> file,
then the compiler will force all dependencies to be dynamic and will generate
errors if dynamic versions could not be found.</p></li>
</ol>

<p>In general, <code>--crate-type=bin</code> or <code>--crate-type=lib</code> should be sufficient for
all compilation needs, and the other options are just available if more
fine-grained control is desired over the output format of a Rust crate.</p>

<h3 id="logging-system" class="section-header"><a href="#logging-system">10.0.5 Logging system(日志系统)</a></h3>
<p>The runtime contains a system for directing <a href="#logging-expressions">logging
expressions</a> to a logging console and/or internal logging
buffers. Logging can be enabled per module.</p>

<p>Logging output is enabled by setting the <code>RUST_LOG</code> environment
variable.  <code>RUST_LOG</code> accepts a logging specification made up of a
comma-separated list of paths, with optional log levels. For each
module containing log expressions, if <code>RUST_LOG</code> contains the path to
that module or a parent of that module, then logs of the appropriate
level will be output to the console.</p>

<p>The path to a module consists of the crate name, any parent modules,
then the module itself, all separated by double colons (<code>::</code>).  The
optional log level can be appended to the module path with an equals
sign (<code>=</code>) followed by the log level, from 1 to 4, inclusive. Level 1
is the error level, 2 is warning, 3 info, and 4 debug. You can also
use the symbolic constants <code>error</code>, <code>warn</code>, <code>info</code>, and <code>debug</code>.  Any
logs less than or equal to the specified level will be output. If not
specified then log level 4 is assumed.  Debug messages can be omitted
by passing <code>--cfg ndebug</code> to <code>rustc</code>.</p>

<p>As an example, to see all the logs generated by the compiler, you would set
<code>RUST_LOG</code> to <code>rustc</code>, which is the crate name (as specified in its <code>crate_id</code>
<a href="#attributes">attribute</a>). To narrow down the logs to just crate resolution,
you would set it to <code>rustc::metadata::creader</code>. To see just error logging
use <code>rustc=0</code>.</p>

<p>Note that when compiling source files that don't specify a
crate name the crate is given a default name that matches the source file,
with the extension removed. In that case, to turn on logging for a program
compiled from, e.g. <code>helloworld.rs</code>, <code>RUST_LOG</code> should be set to <code>helloworld</code>.</p>

<h4 id="logging-expressions" class="section-header"><a href="#logging-expressions">10.0.5.1 Logging Expressions(日志表达式)</a></h4>
<p>Rust provides several macros to log information. Here's a simple Rust program
that demonstrates all four of them:</p>
<pre class="rust "><span class="attribute">#<span class="op">!</span>[<span class="ident">feature</span>(<span class="ident">phase</span>)]</span>
<span class="attribute">#[<span class="ident">phase</span>(<span class="ident">syntax</span>, <span class="ident">link</span>)]</span> <span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">log</span>;

<span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="macro">error</span><span class="macro">!</span>(<span class="string">"This is an error log"</span>)
    <span class="macro">warn</span><span class="macro">!</span>(<span class="string">"This is a warn log"</span>)
    <span class="macro">info</span><span class="macro">!</span>(<span class="string">"this is an info log"</span>)
    <span class="macro">debug</span><span class="macro">!</span>(<span class="string">"This is a debug log"</span>)
}
</pre>

<p>These four log levels correspond to levels 1-4, as controlled by <code>RUST_LOG</code>:</p>

<pre><code class="language-notrust,bash">$ RUST_LOG=rust=3 ./rust
This is an error log
This is a warn log
this is an info log</code></pre>

<h1 id="appendix:-rationales-and-design-tradeoffs" class="section-header"><a href="#appendix:-rationales-and-design-tradeoffs">11 Appendix: Rationales and design tradeoffs(附录:基本原理和设计权衡)</a></h1>
<p><em>TODO</em>.</p>

<h1 id="appendix:-influences-and-further-references" class="section-header"><a href="#appendix:-influences-and-further-references">12 Appendix: Influences and further references<(进一步的影响和参考)/a></h1>
<h2 id="influences" class="section-header"><a href="#influences">12.1 Influences(影响)</a></h2>
<blockquote>
<p>The essential problem that must be solved in making a fault-tolerant
 software system is therefore that of fault-isolation. Different programmers
 will write different modules, some modules will be correct, others will have
 errors. We do not want the errors in one module to adversely affect the
 behaviour of a module which does not have any errors.</p>

<p>— Joe Armstrong</p>

<p>In our approach, all data is private to some process, and processes can
 only communicate through communications channels. <em>Security</em>, as used
 in this paper, is the property which guarantees that processes in a system
 cannot affect each other except by explicit communication.</p>

<p>When security is absent, nothing which can be proven about a single module
 in isolation can be guaranteed to hold when that module is embedded in a
 system [...]</p>

<p>— Robert Strom and Shaula Yemini</p>

<p>Concurrent and applicative programming complement each other. The
 ability to send messages on channels provides I/O without side effects,
 while the avoidance of shared data helps keep concurrent processes from
 colliding.</p>

<p>— Rob Pike</p>
</blockquote>

<p>Rust is not a particularly original language. It may however appear unusual
by contemporary standards, as its design elements are drawn from a number of
"historical" languages that have, with a few exceptions, fallen out of
favour. Five prominent lineages contribute the most, though their influences
have come and gone during the course of Rust's development:</p>

<ul>
<li><p>The NIL (1981) and Hermes (1990) family. These languages were developed by
Robert Strom, Shaula Yemini, David Bacon and others in their group at IBM
Watson Research Center (Yorktown Heights, NY, USA).</p></li>
<li><p>The Erlang (1987) language, developed by Joe Armstrong, Robert Virding, Claes
Wikström, Mike Williams and others in their group at the Ericsson Computer
Science Laboratory (Älvsjö, Stockholm, Sweden) .</p></li>
<li><p>The Sather (1990) language, developed by Stephen Omohundro, Chu-Cheow Lim,
Heinz Schmidt and others in their group at The International Computer
Science Institute of the University of California, Berkeley (Berkeley, CA,
USA).</p></li>
<li><p>The Newsqueak (1988), Alef (1995), and Limbo (1996) family. These
languages were developed by Rob Pike, Phil Winterbottom, Sean Dorward and
others in their group at Bell Labs Computing Sciences Research Center
(Murray Hill, NJ, USA).</p></li>
<li><p>The Napier (1985) and Napier88 (1988) family. These languages were
developed by Malcolm Atkinson, Ron Morrison and others in their group at
the University of St. Andrews (St. Andrews, Fife, UK).</p></li>
</ul>

<p>Additional specific influences can be seen from the following languages:</p>

<ul>
<li>The structural algebraic types and compilation manager of SML.</li>
<li>The attribute and assembly systems of C#.</li>
<li>The references and deterministic destructor system of C++.</li>
<li>The memory region systems of the ML Kit and Cyclone.</li>
<li>The typeclass system of Haskell.</li>
<li>The lexical identifier rule of Python.</li>
<li>The block syntax of Ruby.</li>
</ul>

<div class="footnotes">
<hr>
<ol>

<li id="fn1">
<p>Substitute definitions for the special Unicode productions are
provided to the grammar verifier, restricted to ASCII range, when verifying
the grammar in this document.&nbsp;<a href="#fnref1" rev="footnote">↩</a></p>
</li>

<li id="fn2">
<p>A crate is somewhat analogous to an <em>assembly</em> in the
ECMA-335 CLI model, a <em>library</em> in the SML/NJ Compilation Manager, a <em>unit</em>
in the Owens and Flatt module system, or a <em>configuration</em> in Mesa.&nbsp;<a href="#fnref2" rev="footnote">↩</a></p>
</li>

<li id="fn3">
<p>The "unit" value <code>()</code> is <em>not</em> a sentinel "null pointer" value for
reference slots; the "unit" type is the implicit return type from functions
otherwise lacking a return type, and can be used in other contexts (such as
message-sending or type-parametric code) as a zero-size type.]&nbsp;<a href="#fnref3" rev="footnote">↩</a></p>
</li>

<li id="fn4">
<p>A Rust <code>uint</code> is analogous to a C99 <code>uintptr_t</code>.&nbsp;<a href="#fnref4" rev="footnote">↩</a></p>
</li>

<li id="fn5">
<p>A Rust <code>int</code> is analogous to a C99 <code>intptr_t</code>.&nbsp;<a href="#fnref5" rev="footnote">↩</a></p>
</li>

<li id="fn6">
<p><code>struct</code> types are analogous <code>struct</code> types in C,
the <em>record</em> types of the ML family,
or the <em>structure</em> types of the Lisp family.&nbsp;<a href="#fnref6" rev="footnote">↩</a></p>
</li>

<li id="fn7">
<p>The <code>enum</code> type is analogous to a <code>data</code> constructor declaration in
         ML, or a <em>pick ADT</em> in Limbo.&nbsp;<a href="#fnref7" rev="footnote">↩</a></p>
</li>

<li id="fn8">
<p>This is an M:N scheduler, which is known to give suboptimal
results for CPU-bound concurrency problems.  In such cases, running with the
same number of threads and tasks can yield better results.  Rust has M:N
scheduling in order to support very large numbers of tasks in contexts where
threads are too resource-intensive to use in large number.  The cost of
threads varies substantially per operating system, and is sometimes quite
low, so this flexibility is not always worth exploiting.&nbsp;<a href="#fnref8" rev="footnote">↩</a></p>
</li>

</ol>
</div>

    <footer><p>
Copyright © 2011-2014 The Rust Project Developers. Licensed under the
<a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>
or the <a href="http://opensource.org/licenses/MIT">MIT license</a>, at your option.
</p><p>
This file may not be copied, modified, or distributed except according to those terms.
</p></footer>



</body></html>
